source

사용자가 PHP로 파일을 업로드했는지 어떻게 확인합니까?

factcode 2023. 8. 27. 09:55
반응형

사용자가 PHP로 파일을 업로드했는지 어떻게 확인합니까?

사용자가 업로드한 파일이 올바른 유형인지 확인하기 위해 양식 검증을 수행합니다.하지만 업로드는 선택 사항이므로, 그가 업로드한 것이 없고 나머지 양식을 제출했다면 검증을 건너뛰고 싶습니다.그가 무언가를 업로드했는지 어떻게 확인할 수 있습니까?할 것이다$_FILES['myflie']['size'] <=0일?

다음을 사용할 수 있습니다.

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

문서에서:

파일 이름으로 지정된 파일이 HTTP POST를 통해 업로드된 경우 TRUE를 반환합니다.이 기능은 악의적인 사용자가 스크립트가 작동하지 않아야 하는 파일(예: /etc/passwd)에서 작업하도록 속이지 않도록 하는 데 유용합니다.

업로드된 파일을 사용하여 수행한 모든 작업이 사용자에게 또는 동일한 시스템의 다른 사용자에게 자신의 콘텐츠를 노출할 가능성이 있는 경우 이러한 종류의 검사는 특히 중요합니다.

편집: 다음과 같은 경우를 대비하여 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;
}

이 코드는 저에게 효과가 있었습니다.제가 여러 파일 업로드를 사용하고 있어서 업로드가 있었는지 확인해야 했습니다.

HTML 파트:

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

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

@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;
}
<!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>

하지만 조심하세요.사용자는 모든 유형의 파일을 업로드할 수 있으며 악성 또는 php 파일을 업로드하여 서버 또는 시스템을 해킹할 수도 있습니다.이 스크립트에는 몇 가지 검증이 있어야 합니다.감사해요.

사용해야 합니다.$_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;
}

is_uploaded_file()업로드된 파일인지 로컬 파일인지(보안 목적)를 확인하는 데 특히 유용합니다.

그러나 사용자가 파일을 업로드했는지 여부를 확인하려면 다음을 사용합니다.$_FILES['file']['error'] == UPLOAD_ERR_OK.

파일 업로드 오류 메시지에 대한 PHP 설명서를 참조하십시오.파일이 없는지만 확인하려면 다음을 사용합니다.UPLOAD_ERR_NO_FILE.

당신의 코드를 확인했고 당신은 이것을 시도해야 한다고 생각합니다.

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

일반적으로 사용자가 파일을 업로드할 때 PHP 서버는 예외적인 실수나 오류를 감지하지 않으며, 이는 파일이 성공적으로 업로드되었음을 의미합니다.https://www.php.net/manual/en/reserved.variables.files.php#109648

if ( boolval( $_FILES['image']['error'] === 0 ) ) {
    // ...
}

언급URL : https://stackoverflow.com/questions/946418/how-to-check-whether-the-user-uploaded-a-file-in-php

반응형