【发布时间】:2015-10-25 07:07:31
【问题描述】:
我做了一个可以上传图片到服务器的PHP应用程序。它大部分时间都可以正常工作,但不会上传一些图片。
您可以在此处下载所有文件,包括一张有效的图片和一张无效的图片:https://drive.google.com/file/d/0BwoIBS8cNsz4Rjl0eERMb2FndUk/view?usp=sharing
这是我的 PHP 代码(文件名:upload.php):
<?php
if(isset($_POST["submit"])) {
$target_dir = "slike/";
$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
$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"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $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.";
}
}
}
else{
echo "Sorry, there was an error uploading your file.";
}
?>
这是我的 HTML 代码(文件名:index.php):
<!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" required>
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
我在 Windows 8 上使用 Wamp 服务器,我没有更改任何配置。
(英语不是我的母语,我希望得到更多关于代码的答案作为语法更正。)
【问题讨论】:
-
在代码中的关键点放置调试语句,以查看无法上传的文件发生了什么
-
“大部分时间都可以正常工作,但是有些图片上传不了。”上传失败有什么错误吗?上传的图片和不上传的图片有什么不同吗?
-
可能你应该在 php.ini 中更改 'upload_max_filesize' 和 'post_max_size' 的值。尝试为此设置更大的价值,然后再试一次。
-
@TismonVarghese 就是这样 :) 谢谢!