【发布时间】:2015-08-05 16:06:57
【问题描述】:
我想在我的主页上上传图片。 我正在使用 w3schools 的脚本来执行此操作:
这是upload.html
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
这是upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !="jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
我已经创建了一个文件夹 /var/www/uploads/ 尝试上传 3KB jpeg 时,我得到以下输出:
File is an image - image/jpeg.
Sorry, there was an error uploading your file.
Array ( [fileToUpload] => Array ( [name] => Test Bild Website Upload.jpg [type] => image/jpeg [tmp_name] => /tmp/phpyxW0TX [error] => 0 [size] => 2999 ) )
我是 php 的初学者,我真的不知道问题出在哪里。 也许有人可以帮助我解决这个问题。 :)
【问题讨论】:
-
您对“/var/www/uploads/”文件夹的权限是什么,它需要由您的网络服务器用户拥有或可写,最常见的是 www-data 或 apache
-
确保`/var/www/uploads/`的权限设置为
755 -
您的
move_uploaded_file函数返回 false。当文件不是有效的上传文件或文件是有效的上传文件但由于某种原因无法移动时,会发生这种情况。检查您上传到的文件夹的权限。也许你需要确保你有读写权限。 -
在哪里可以更改文件夹的权限?该服务器在 Debian 7 上运行。编辑:刚刚在 Filezilla 上找到它。但问题依然存在。
-
你有 Filezilla 吗?只需右键单击文件夹并选择权限,然后输入 755