好的,非常简单的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
)
)
有什么理由说这不起作用吗?
答案 0 :(得分:0)
使用此代码测试目标目录是否实际存在可写。
如果您的目标目录不可写,则在Mac上,您可以在终端中运行它。
ls -lah /full/path/to/the/survey/directory
并检查群组和所有者,它应该由_www
拥有,就像您网站上的其他目录一样。如果您的Apache用户不同,请根据需要进行调整。
如果不是,则运行以下命令:
sudo chown _www:_www /full/path/to/the/survey/directory/
sudo chmod 0755 /full/path/to/the/survey/directory/
<?php
$target_dir = home_url() . "/wp-content/uploads/survey/";
$target_file = $target_dir . basename($_FILES["frontImage"]["name"]);
// check if dir is writable
if ( !is_writable($target_dir)) {
echo $target_dir . ' is not writable';
}
else {
// proceed to write the file there
// either set a boolean flag $writable = 1 or
// insert into if/else chain
}
// check if dir exists
if (!file_exists($target_dir)){
echo $target_dir . ' does not exist';
}
else {
// proceed with the rest of your logic
// either set a boolean flag $dirExists = 1 or
// insert this into your if/else chain
}