【发布时间】:2015-10-01 16:51:29
【问题描述】:
好的,非常简单的 w3schools 上传脚本,我尝试实现,但一直收到错误消息。
作为参考,我使用的是 WordPress,需要创建自定义上传方法,所以我不能使用自定义字段等。
关于此的 HTML 部分:
<form method="post" id="form" enctype="multipart/form-data">
<input type="file" name="frontImage" id="frontImage">
PHP 方面:
$target_dir = home_url() . "/wp-content/uploads/survey/";
$target_file = $target_dir . basename($_FILES["frontImage"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["frontImage"]["tmp_name"]);
if($check !== false) {
$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["frontImage"]["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["frontImage"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["frontImage"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
好的,我得到的错误是:
"Sorry, there was an error uploading your file."
这意味着 move_uploaded_file() 部分失败。
如果我 print_r($_FILES) 我得到:
Array
(
[frontImage] => Array
(
[name] => Everest_kalapatthar_crop.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpHw9BcP
[error] => 0
[size] => 93053
)
)
这有什么不工作的原因吗?
【问题讨论】:
-
什么是 $target_dir ?它是您目录的正确路径吗?如果是,请确保文件夹权限设置为 0777
-
输出
$target_dir确保它是有效的。 -
@EM-Creations target_dir 和 target_file 都是正确的路径
标签: php wordpress forms upload