在php中获取文件上传错误

时间:2016-10-17 05:31:22

标签: php file-upload error-handling runtime-error

任何人都可以使用我的代码推断出这里可能出现的问题吗?当我尝试上传超过8 MB的PDF文件时,这就是我得到的消息:

  

出错了[没有上传文件]文件已在服务器上。

这是我输入的代码:

    <?php
    $name = $_FILES['file']['name']; 
    $storefile_loc = "uploads/"; 
    $storefile_path = $storefile_loc.basename($name);

    //$get_ext=explode(".",$_FILES['file']['name']); //separates file name from extension
    //$ext=end($get_ext); //gets the extension from above explosion
    $txtFileType = pathinfo($storefile_path,PATHINFO_EXTENSION);
    $goodext = array("txt","doc","odt","docx"); //array of extensions for app

    //Check if files are .txt (.doc, and .pdf functionality to be added)
    if (isset($_POST["submit"])){ //checks if form has been submitted
        //$check=mime_content_type($name);
        if (($_FILES['file']['type'] == "text/plain")
        ||($_FILES['file']['type'] == "application/pdf")
        ||($_FILES['file']['type'] == "application/vnd.oasis.opendocument.text")
        ||($_FILES['file']['type'] == "application/msword")
        ||($_FILES['file']['type'] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
        &&(in_array($txtFileType,$goodext))){
            echo "Uploading File...";
        }
        else {
            echo "You can only upload a txt/doc/docx/pdf/odt file.";
        }
    }
    else {
        echo "Something went wrong [No file uploaded]";
    }

    //Check if file already exists. Probably won't need this
    if (file_exists($storefile_path)){ //this instead of $name because it's checking server
        echo "File already on server.";
    }

    //Check file size
    if  ($_FILES['file']['size'] > 2000000){
        echo "File is too large.";
    }   


    //Way to upload permanently. Probably won't need this
    /*
    if (move_uploaded_file($_FILES['file']['tmp_name'], $storefile_path)){
        echo "The file '".basename($_FILES['file']['name'])."' has been uploaded.";
    }
    else {
        echo "Something went wrong when uploading your file.";
    }
    */

    ?>

我也注意到第2行和第36行的错误。我的代码有问题吗?或者是Apache?

2 个答案:

答案 0 :(得分:0)

尝试在php.ini中增加这些设置,默认大小(通常)为8MB

  ; Maximum allowed size for uploaded files.
  upload_max_filesize = 40M;
  ; Must be greater than or equal to upload_max_filesize
  post_max_size = 40M;

之后,您必须重新启动服务器才能应用这些设置。

这意味着PHP将文件上传大小限制为这两个设置。你可能不需要40M,但你应该把它增加到你想要上传的最大文件的120%,这会给你一些喘息的空间。

这通常是我在服务器上配置的第一件事,我通常会做大约80MB,除此之外,我的客户更容易使用sFTP。

答案 1 :(得分:0)

您需要添加通知错误行

$name = $_FILES['file']['name'];

if  ($_FILES['file']['size'] > 2000000){
    echo "File is too large.";
}

进入isset(&#39; POST&#39;)

if (isset($_POST["submit"])){
  $name = $_FILES['file']['name'];
  ...
  if  ($_FILES['file']['size'] > 2000000){
    echo "File is too large.";
  }
}