我使用croppie.js创建了一个图像上传系统来裁剪图像,图像已成功提交到数据库,但无法存储到目录中。我尝试了print_r($_POST);
,但收到一个错误消息,说file_put_contents failed to open stream...
。我不知道为什么会这样,因为我的文件目录($dir
)是正确的,但是我确实尝试在查询之后插入file_put_contents($dir.$photo, $data);
,但没有执行任何操作,但是将图像提交到数据库中并仍然显示file_put_contents错误。
以下是我的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);
?>
答案 0 :(得分:2)
替换
$dir = "../photos/";
使用
$dir = __DIR__."/../photos/";
file_put_contents()
期望完整路径,而不是相对路径。