简体   繁体   中英

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.

** I want to upload the image in the web server. **

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. What is wrong with the code above?

Edited I changed the path name into $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.

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:

//__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())");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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