【发布时间】:2015-04-05 14:49:35
【问题描述】:
我有一个使用uploads.php 的表单。见下文:
<?php
include 'config/database.php';
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// 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" && $imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx") {
echo "Sorry, only JPG, JPEG, PNG, DOC, PDF & 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.";
}
}
header("Location: http://same-page-the-form-is-on.php");
?>
表格(index.php):
<form id="myForm" action="uploads.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" id="simple-post" value="Upload File Here" name="submit">
</form>
<?php
$dir = "uploads/";
$files = array_diff(scandir($dir), array('..', '.'));
echo "<select>";
foreach($files as $item ) {
echo "<option value='.$item.'>" . $item . "</option>\n";
}
echo "</select>";
?>
因此,根据上传时发生的情况,无论是文件已经存在、文件太大还是文件扩展名错误,我希望在 index.php 上显示服务器端错误消息 .解决这个问题的正确方法是什么? AJAX?
【问题讨论】:
-
AJAX - 这是非常好的选择,但您也可以使用 GET 重定向到同一页面(uploads.php?
= ) -
啊,这是个好主意。我会调查一下并在这里报告,谢谢!
-
您可以将错误存储在会话变量中并重定向回来并显示您存储在会话中的那些错误。然后终止会话以防止再次显示错误。
标签: php ajax file-upload