简体   繁体   English

PHP:从base64字符串中获取图像并将其存储在路径中

[英]PHP: get image from base64 string and store it in the path

Here's the PHP function that adds a new data into the MySQL database. 这是PHP函数,它将新数据添加到MySQL数据库中。

** I want to upload the image in the web server. **我想在Web服务器上传图像。 ** **

public function addNewCategory($category_title, $strImage) {

    // get the image from the base64 string.
    $strImage = base64_decode($strImage);
    $image = imagecreatefromstring($strImage);
    if($image !== false) {
        header('Content-Type: image/png');
        imagepng($image);
        imagedestroy($image);
    }

    // set the path name of where the image is to be stored.
    $path = $_SERVER['SERVER_NAME']."/uploads/".$category_title.".png";

    // save the image in the path.
    file_put_contents($path, $image);

    // insert category and the image path into the MySQL database.
    $result = mysqli_query($this->db->connect(), "INSERT INTO category(category_title, path, created_at) VALUES ('$category_title', '$path', NOW())");

    if ($result) {
        return mysqli_fetch_array($result);
    } else {
        return false;
    }
}

With that function, the path variable is stored in the database, but the image is not actually stored in the path. 使用该函数, path变量存储在数据库中,但图像实际上并未存储在路径中。 What is wrong with the code above? 上面的代码有什么问题?

Edited I changed the path name into $path = $_SERVER['SERVER_NAME']."/MyProject/uploads/".$category_title.".png"; 编辑后我将路径名改为$path = $_SERVER['SERVER_NAME']."/MyProject/uploads/".$category_title.".png"; . Now the path value in the database turns out to be what I expected, but it seems like the image itself is not actually put in the path. 现在数据库中的路径值证明是我所期望的,但似乎图像本身并没有实际放入路径中。

I added a new row to the database, manually typed the path in the browser to check if the image I sent is properly stored in the path, but the web server returns error 404. 我向数据库添加了一个新行,在浏览器中手动键入路径以检查我发送的图像是否正确存储在路径中,但Web服务器返回错误404。

To write file on server you need to set path, relative to your folder system on server. 要在服务器上写入文件,您需要相对于服务器上的文件夹系统设置路径。 To store data in DB you need web path to your image: 要在数据库中存储数据,您需要指向图像的Web路径:

//__DIR__ - path to your current script folder
$server_path = __DIR__."/uploads/".$category_title.".png";

// save the image in the server path.
file_put_contents($server_path, $image);

//Web path to your image
$web_path = $_SERVER['SERVER_NAME']."/uploads/".$category_title.".png";

//Write to DB web path of the image
$result = mysqli_query($this->db->connect(), "INSERT INTO category(category_title, path, created_at) VALUES ('$category_title', '$web_path', NOW())");

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

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