Php 文件\u将\u内容存储到目录中失败
我用cropie.js创建了一个图像上传系统来裁剪已经上传的图像,图像已经成功提交到数据库中,但无法存储到目录中。我尝试了Php 文件\u将\u内容存储到目录中失败,php,file-put-contents,Php,File Put Contents,我用cropie.js创建了一个图像上传系统来裁剪已经上传的图像,图像已经成功提交到数据库中,但无法存储到目录中。我尝试了print\r($\u POST)我得到一个错误,说文件\u put\u内容无法打开流…。我不知道为什么会发生这种情况,因为我的文件目录($dir)是正确的,但我确实尝试插入了文件内容($dir.$photo,$data)在我的查询之后,它什么也没做,只是将图像提交到数据库中,并且仍然打印文件\u put\u内容错误 下面是我的PHP文件 <?php // va
print\r($\u POST)代码>我得到一个错误,说文件\u put\u内容无法打开流…
。我不知道为什么会发生这种情况,因为我的文件目录($dir
)是正确的,但我确实尝试插入了文件内容($dir.$photo,$data)代码>在我的查询之后,它什么也没做,只是将图像提交到数据库中,并且仍然打印文件\u put\u内容错误
下面是我的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/";
与
file\u put\u contents()
需要完整路径,而不是相对路径。请添加完整的错误消息。您似乎在使用随机数生成文件名。有时它会匹配现有文件并覆盖它。那么如何修复@FelippeDuarte$dir=“../photos/”代码>应该是$dir=\uuuuuu dir\uuuuu./../photos/”代码>哇!谢谢,现在一切都好了。一开始我确实犯了一个错误,忘记了斜杠“/”,但现在一切都完成了@FelippeDuarte
$dir = __DIR__."/../photos/";