在网页上上传和显示文件

时间:2014-03-19 13:02:46

标签: php file upload

以下代码是在upload.php页面上传和显示文件,并且工作正常。我遇到的问题是,如果我将upload.php页面的url复制并粘贴到新的网页中,它就不会显示文件。

upload.php代码

<?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>

1 个答案:

答案 0 :(得分:1)

如果您将代码缩进为人类可读,您会发现整个服务器端代码块都包含在此条件中:

if (isset($_FILES['file_upload'])) {
    // all of your code
}

这意味着如果将file_upload值发布到表单,则所有服务器端代码都将仅执行 。将URL复制/粘贴到新的浏览器窗口并调用该请求时,您将调用没有表单值的GET请求。由于您未在此请求中上传文件,因此isset()条件的计算结果为false,并且您的代码未执行。

您应该将您的功能分为两组:

  1. 处理上传。
  2. 显示数据的当前状态。
  3. 处理上传的代码只应在上传时执行。用于显示数据的代码应始终执行。

    如果我正确阅读您的代码,您需要做的就是将最后几部分分开:

    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);
    }