file_put_contents 无法将图像存储到目录中

file_put_contents failed in storing image into directory

我用 croppie.js 创建了一个图像上传系统来裁剪上传的图像,图像已成功提交到数据库但未能存储到目录中。我试过 print_r($_POST);,但我收到一条错误消息 file_put_contents failed to open stream...。我不知道为什么会这样,因为我的文件目录 ($dir) 是正确的,但我确实尝试在我的查询后插入 file_put_contents($dir.$photo, $data);,除了将图像提交到数据库中并仍然打印 [=23] =]错误。

下面是我的PHP文件;

<?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);
?>

替换

$dir = "../photos/";

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

file_put_contents() 需要完整路径,而不是相对路径。