PHP: get image from base64 string and save it in path

Here's a PHP function that adds new data to the MySQL database.

** I want to upload an image to a 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;
    }
}

Using this function, the variable pathis stored in the database, but the image is not actually saved in the path. What is wrong with the code above?

Edited I changed the name of the path to $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 looks like the image itself is not actually inserted in the path.

I added a new row to the database by manually typing the path in the browser to check if the image in the path was saved correctly, but the web server returns a 404 error.

+4
source share
1

, . - :

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

Source: https://habr.com/ru/post/1618177/


All Articles