phpfile-put-contents

file_put_contents failed in storing image into directory


I created an image upload system with croppie.js to crop image been uploaded, image is been submitted successfully into database but failed storing into directory. I tried print_r($_POST); and i got an error saying file_put_contents failed to open stream.... I don't know why this is happening because my file directory ($dir) is correct but i did try inserting the file_put_contents($dir.$photo, $data); after my query which did nothing but submits image into database and still print file_put_contents error.

Below is my PHP file;

<?php
    // variables
    $error = "";

    if(isset($_POST['imagebase64'])) {
        $data = $_POST['imagebase64'];

        // generate random name for image file in digits
        $min_rand = rand(0, 1000);
        $max_rand = rand(10000000, 1000000000);
        $rand = rand($min_rand, $max_rand);
        $name_file = "img_".$rand;

        // directory to save image file
        $dir = "../photos/";

        // image file with directory, new name and extention
        $photo = $name_file.".png";

        list($type, $data) = explode(';', $data);
        list(, $data)      = explode(',', $data);
        $data = base64_decode($data);

        // store image in folder
        file_put_contents($dir.$photo, $data);

        // prepare query
        // `profile_photo`
        $query = "UPDATE profile_photo SET photo = ? WHERE id = ?";

        // `profile_photo_history`
        $query = "INSERT INTO profile_photo_history(id, photo) VALUES(?, ?)";

        if ($stmt = mysqli_prepare($db, $query)) {
            // bind variables to the prepared statement as parameters
            // `profile_photo`
            $query = "UPDATE profile_photo SET photo = ? WHERE id = ?";
            $stmt = mysqli_prepare($db, $query);
            mysqli_stmt_bind_param($stmt, "si", $photo, $id);
            if (mysqli_stmt_execute($stmt)) {
                // `profile_photo_history`
                $query = "INSERT INTO profile_photo_history(id, photo) VALUES(?, ?)";
                $stmt = mysqli_prepare($db, $query);
                mysqli_stmt_bind_param($stmt, "is", $id, $photo);
                mysqli_stmt_execute($stmt);

                // print_r($_POST);
                // direct user back to profile page
                header("location: ../../profile.php?profile_photo_changed");
            } else {
                $error = '<font color="#dc3545">Oops! Something went wrong. Please try again later</font>';
            }
        }
        // close statement
        mysqli_stmt_close($stmt);
    }
    // close db connection
    mysqli_close($db);
?>

Solution

  • Replace

    $dir = "../photos/";
    

    With

    $dir = __DIR__."/../photos/";
    

    file_put_contents() expect a full path, not a relative path.