我正在尝试上传图片,如下所示w3schools,但它始终显示错误
Sorry, there was an error uploading your file.
PHP
<?php
if(!isset($_POST["submit"])){
die('Error');
}
$target_dir = "/var/www/img/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
它已在Windows 10中运行。现在,错误似乎已完成,但正在移动文件或其他错误。
操作系统:Ubuntu 18.04
PHP版本:7.3
Apache2
在php.ini中,设置了file_uploads = On。
答案 0 :(得分:0)
您正在使用的功能的文档页面move_uploaded_file()
描述了发生故障时的行为。
成功返回TRUE。
如果filename不是有效的上传文件,则不会执行任何操作,并且 move_uploaded_file()将返回FALSE。
如果文件名是有效的上传文件,但无法移动某些文件名 原因,将不会执行任何操作,并且move_uploaded_file()将返回 假。此外,还会发出警告。
您可以做的第一件事是enable error and warning reporting,这样您就可以查看是否发出警告。
这样,您将知道文件名或实际文件移动是否有问题-这将指示权限问题。
答案 1 :(得分:0)
It may be due to permission to directory you created in /var/www/ folder.
You can check your apache user by using following command
ps -ef | egrep '(httpd|apache2|apache)' | grep -v `whoami` | grep -v root | head -n1 | awk '{print $1}'
You will get the apache user.After that give permission to apache user to access the directory.In my case apache user is daemon so i give permission to this user to access the img directory.
chown -R daemon:daemon img