下面的代码在upload.php页面上上传和显示文件,并且工作正常。我遇到的问题是,如果我将upload.php页面的url复制并粘贴到新网页中,则不会显示文件。
upload.php code
<?php
if (isset($_FILES['file_upload'])) {
$file = $_FILES['file_upload'];
$name = $file['name'];
$type = $file['type'];
$tmp_location = $file['tmp_name'];
$upload = 'uploads';
$final_destination = $upload.'/'.$name;
$error = $file['error'];
$max_upload_size = 2097152;
$size = $file['size'];
$allowedImageTypes = array( 'image/png', 'image/jpeg', 'image/gif', );
function imageTypeAllowed($imageType){
global $allowedImageTypes;
if(in_array($imageType, $allowedImageTypes)){
return true;
}
else{
return false;
}
}
//Check for errors
if($error > 0 || is_array($error)){
die("Sorry an error occured");
}
//Check if file is image
//Only required if image is only whjat we need
if(!getimagesize($tmp_location)){
die("Sorry, you can only upload image types");
}
if(!imageTypeAllowed($type)){
die("Sorry, file type is not allowed");
}
if(file_exists($final_destination)){
$final_destination = $upload.'/'.time().$name;
}
if(!move_uploaded_file($tmp_location, $final_destination)){
die("Cannot finish upload, something went wrong");
}
$handle = opendir('uploads');
if($handle){
while(($entry = readdir($handle)) !== false){
if($entry != '.' && $entry != '..'){
echo "<a href="uploads/$entry">$entry</a><br>";
}
}
closedir($handle);
}
}
?>
<h2>File Successfully uploaded!</h2>
如果您将代码缩进以使人类可读,您会发现整个服务器端代码块被包装在这个条件中:
if (isset($_FILES['file_upload'])) {
// all of your code
}
这意味着如果一个file_upload
值被post到表单中,那么所有的服务器端代码将只执行。当您将URL复制/粘贴到一个新的浏览器窗口并调用该请求时,您调用的是一个没有表单值的GET请求。由于您没有在此请求中上传文件,因此isset()
条件的计算结果为false,并且您的代码不会执行。
你应该把你的功能分成两组:
- 正在处理上传
- 显示数据的当前状态。
处理上传的代码应该只在出现上传时执行。显示数据的代码应该始终执行。
如果我没看错你的代码,你应该做的就是把最后几部分分开:
if (isset($_FILES['file_upload'])) {
// the rest of your code
}
$handle = opendir('uploads');
if($handle){
while(($entry = readdir($handle)) !== false){
if($entry != '.' && $entry != '..'){
echo "<a href="uploads/$entry">$entry</a><br>";
}
}
closedir($handle);
}