php PHP如何检查用户是否上传了文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/946418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:24:38  来源:igfitidea点击:

How to check whether the user uploaded a file in PHP?

php

提问by Click Upvote

I do some form validation to ensure that the file a user uploaded is of the right type. But the upload is optional, so I want to skip the validation if he didn't upload anything and submitted the rest of the form. How can I check whether he uploaded something or not? Will $_FILES['myflie']['size'] <=0work?

我进行了一些表单验证以确保用户上传的文件类型正确。但是上传是可选的,所以如果他没有上传任何东西并提交了表单的其余部分,我想跳过验证。我如何检查他是否上传了一些东西?会$_FILES['myflie']['size'] <=0工作吗?

回答by karim79

You can use is_uploaded_file():

您可以使用is_uploaded_file()

if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
    echo 'No upload';
}

From the docs:

从文档:

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

如果由 filename 命名的文件是通过 HTTP POST 上传的,则返回 TRUE。这有助于确保恶意用户没有试图欺骗脚本处理它不应该处理的文件——例如,/etc/passwd。

如果对上传的文件所做的任何操作可能会向用户甚至同一系统上的其他用户透露其内容,则此类检查尤其重要。

EDIT: I'm using this in my FileUpload class, in case it helps:

编辑:我在我的 FileUpload 类中使用它,以防它有帮助:

public function fileUploaded()
{
    if(empty($_FILES)) {
        return false;       
    } 
    $this->file = $_FILES[$this->formField];
    if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
        $this->errors['FileNotExists'] = true;
        return false;
    }   
    return true;
}

回答by pranjal

This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.

这段代码对我有用。我正在使用多个文件上传,所以我需要检查是否有任何上传。

HTML part:

HTML部分:

<input name="files[]" type="file" multiple="multiple" />

PHP part:

PHP部分:

if(isset($_FILES['files']) ){  


foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){

      if(!empty($_FILES['files']['tmp_name'][$key])){

    //  things you want to do
    }
}

回答by doub1eHyman

@karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.

@karim79 有正确的答案,但我不得不重写他的例子以满足我的目的。他的示例假设提交的字段的名称是已知的并且可以硬编码。我更进一步,并创建了一个函数,该函数可以告诉我是否上传了任何文件,而无需知道上传字段的名称。

/**
 * Tests all upload fields to determine whether any files were submitted.
 * 
 * @return boolean
 */
function files_uploaded() {

    // bail if there were no upload forms
   if(empty($_FILES))
        return false;

    // check for uploaded files
    $files = $_FILES['files']['tmp_name'];
    foreach( $files as $field_title => $temp_name ){
        if( !empty($temp_name) && is_uploaded_file( $temp_name )){
            // found one!
            return true;
        }
    }   
    // return false if no files were found
   return false;
}

回答by shiv

<!DOCTYPE html>
<html>
<body>

<form action="#" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input name="my_files[]" type="file" multiple="multiple" />
    <input type="submit" value="Upload Image" name="submit">
</form>


<?php

 if (isset($_FILES['my_files']))
  {
    $myFile = $_FILES['my_files'];
    $fileCount = count($myFile["name"]);


        for ($i = 0; $i <$fileCount; $i++)
         {
           $error = $myFile["error"][$i]; 

            if ($error == '4')  // error 4 is for "no file selected"
             {
               echo "no file selected";
             }
            else
             {

               $name =  $myFile["name"][$i];
               echo $name; 
               echo "<br>"; 
               $temporary_file = $myFile["tmp_name"][$i];
               echo $temporary_file;
               echo "<br>";
               $type = $myFile["type"][$i];
               echo $type;
               echo "<br>";
               $size = $myFile["size"][$i];
               echo $size;
               echo "<br>";



               $target_path = "uploads/$name";   //first make a folder named "uploads" where you will upload files


                 if(move_uploaded_file($temporary_file,$target_path))
                  {
                   echo " uploaded";
                   echo "<br>";
                   echo "<br>";
                  }
                   else
                  {
                   echo "no upload ";
                  }




              }
        }  
}
        ?>


</body>
</html>

But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.

但要警惕。用户可以上传任何类型的文件,也可以通过上传恶意或 php 文件来入侵您的服务器或系统。在这个脚本中应该有一些验证。谢谢你。

回答by Simon Backx

You should use $_FILES[$form_name]['error']. It returns UPLOAD_ERR_NO_FILEif no file was uploaded. Full list: PHP: Error Messages Explained

你应该使用$_FILES[$form_name]['error']. UPLOAD_ERR_NO_FILE如果没有上传文件,则返回。完整列表:PHP:错误消息说明

function isUploadOkay($form_name, &$error_message) {
    if (!isset($_FILES[$form_name])) {
        $error_message = "No file upload with name '$form_name' in form.";
        return false;
    }
    $error = $_FILES[$form_name]['error'];

    // List at: http://php.net/manual/en/features.file-upload.errors.php
    if ($error != UPLOAD_ERR_OK) {
        switch ($error) {
            case UPLOAD_ERR_INI_SIZE:
                $error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
                break;

            case UPLOAD_ERR_FORM_SIZE:
                $error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
                break;

            case UPLOAD_ERR_PARTIAL:
                $error_message = 'The uploaded file was only partially uploaded.';
                break;

            case UPLOAD_ERR_NO_FILE:
                $error_message = 'No file was uploaded.';
                break;

            case UPLOAD_ERR_NO_TMP_DIR:
                $error_message = 'Missing a temporary folder.';
                break;

            case UPLOAD_ERR_CANT_WRITE:
                $error_message = 'Failed to write file to disk.';
                break;

            case UPLOAD_ERR_EXTENSION:
                $error_message = 'A PHP extension interrupted the upload.';
                break;

            default:
                $error_message = 'Unknown error';
            break;
        }
        return false;
    }

    $error_message = null;
    return true;
}

回答by Gaurav

I checked your code and think you should try this:

我检查了你的代码,认为你应该试试这个:

if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name'])) 
    {
        echo 'No upload';
    }   
    else
        echo 'upload';

回答by TD_Nijboer

is_uploaded_file()is great to use, specially for checking whether it is an uploaded file or a local file (for security purposes).

is_uploaded_file()非常好用,特别是用于检查它是上传的文件还是本地文件(出于安全目的)。

However, if you want to check whether the user uploaded a file, use $_FILES['file']['error'] == UPLOAD_ERR_OK.

但是,如果要检查用户是否上传了文件,请使用$_FILES['file']['error'] == UPLOAD_ERR_OK.

See the PHP manual on file upload error messages. If you just want to check for no file, use UPLOAD_ERR_NO_FILE.

请参阅有关文件上传错误消息的 PHP 手册。如果您只想检查没有文件,请使用UPLOAD_ERR_NO_FILE.