简体   繁体   English

如何在php变量中的服务器上存储base64映像?

[英]How to Store base64 image on server which is in php variable?

I am trying to upload a base64 image to server so I converted it into image but it not getting uploaded on the server. 我正在尝试将base64映像上载到服务器,因此我将其转换为映像,但未在服务器上上载。 The error I am getting while uploading the image is: 我在上传图片时遇到的错误是:

Notice: Undefined index: 584fb34801024.png in /home/dev/public_html/wp-content/plugins/paypal-frontend-registration/advertise_step_three.php on line 45 {"success":0,"message":"Server error. Could not upload."} 注意:/home/dev/public_html/wp-content/plugins/paypal-frontend-registration/advertise_step_three.php在第45行{“ success”:0,“ message”:“服务器错误。未定义的索引:584fb34801024.png无法上传。“}

Here is the code I am trying: 这是我正在尝试的代码:

$sign_img=$_POST['hdn_sign_img'];
$sign_img=str_replace('\"','',$sign_img);
$imageData = $sign_img;
list($type, $imageData) = explode(';', $imageData);
list(,$extension) = explode('/',$type);
list(,$imageData)      = explode(',', $imageData);
$fileName = uniqid().'.'.$extension;
$imageData = base64_decode($imageData);

$data = file_put_contents($fileName, $imageData);
var_dump($data);

$target = '/home/dev/public_html/wp-content/uploads';
$result = move_uploaded_file( $_FILES[$fileName], $target);

if($result){
    $response["success"] = 1;
    $response["message"] = "Upload Successful.";
    die(json_encode($response));
}else{
    $response["success"] = 0;
    $response["message"] = "Server error. Could not upload.";
    die(json_encode($response));
}

If you really want to store it in a file without using the most common PHP uploading method, you can use file_put_contents() . 如果您确实想将其存储在文件中而不使用最常用的PHP上传方法,则可以使用file_put_contents()

file_put_contents('/path/to/filename.ext', $imageData);

And voila. 和瞧。 It's saved to your server. 它已保存到您的服务器。

Example from PHP.net 来自PHP.net的示例

Here's an example for move_uploaded_file() 这是move_uploaded_file()的示例

$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
   if ($error == UPLOAD_ERR_OK) {
       $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        // basename() may prevent filesystem traversal attacks;
        // further validation/sanitation of the filename may be appropriate
        $name = basename($_FILES["pictures"]["name"][$key]);
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

Some reading 一些阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM