我正在尝试使用以下代码上传图片:
<form action="upload_photo.php" method="post" enctype="multipart/form-data">
<p>
Upload a new photo to the server:<br/><br/><br/>
<input type="file" name="myphoto"/><br/><br/>
<input type="submit" value="Upload photo"/>
</p>
</form>
// This function is included from another .php file
function checkUploadedPhoto() {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["myphoto"]["name"]);
if(isset($_FILES['myphoto']) AND $_FILES['myphoto']['error'] == 0) {
// Check size
if($_FILES['myphoto']['size'] <= 1000000) {
// Get extension name
$fileInfo = pathinfo($_FILES['myphoto']['name']);
$upload_extension = $fileInfo['extension'];
$allowed_extensions = array('jpg', 'jpeg', 'gif', 'png');
// Check if the file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
}
// Check if the file has a correct, expected extension
if(in_array($upload_extension, $allowed_extensions)) {
if(move_uploaded_file($_FILES['myphoto']['tmp_name'], $target_file)) {
return true;
}
}
else
echo "error3";
}
else
echo "error2";
}
else
echo "error1";
echo "<pre>". print_r($_FILES) ."</pre>";
echo "Error code: " .$_FILES['myphoto']['error'] ."<br/>";
return false;
}
if(checkUploadedPhoto()) {
header("Location: index.php");
}
else {
echo "upload error";
}
即使错误代码为0
,上传失败。这是一个许可问题吗?我似乎无法分辨出问题出在哪里。
我检查的其他参考资料虽然没有帮助:
link1 / link2 / link3 / W3Schools PHP upload
这是我应用的结构:
我添加此测试以检查uploads/
目录是否可写,&amp;事实证明它无法访问:
// This condition is true
if (!is_writeable('uploads/' . $_FILES['myphoto']['name'])) {
die("Cannot write to destination file");
}
我将目标目录从"uploads/"
更改为"/uploads/"
&amp;它适用于 localhost ,但不适用于托管服务器。
答案 0 :(得分:1)
我找到了解决方案。我不得不改变:
$target_dir = "uploads/";
到
$target_dir = dirname(__FILE__) ."/uploads/";
dirname(__FILE__)
指的是文件的完整路径和文件名。