检查PHP表单上的上载文件扩展名

时间:2015-05-10 13:05:00

标签: php forms

我有一个PHP联系人,可以检查提交中的错误。在一个部分,我检查文件上传的特定扩展名。如果不允许扩展(即PHP文件),那么表单应该产生错误消息(并且不上传文件)。除了这一个,我的所有其他错误消息都有效。请查看下面的代码,如果您发现问题(请原因我看不出有什么问题),请告诉我。

// *** FILE UPLOAD INFO *** //
//Get the uploaded file information
$name_of_uploaded_file =
    basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
    substr($name_of_uploaded_file,
    strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
    $_FILES["uploaded_file"]["size"]/1024;//size in KBs

//FILE UPLOAD
        //Settings
        $max_allowed_file_size = 5000; // size in KB
        $allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "png", "zip", "pdf", "doc", "rtf");
        // Validations
        if($size_of_uploaded_file > $max_allowed_file_size )
        {
          $errors .= "<li>Size of file should be less than $max_allowed_file_size </li>";
        }
        //------ Validate the file extension -----
        $allowed_ext = 0;
        for($i=0; $i<sizeof($allowed_extensions); $i++)
        {
          if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
          {
            $allowed_ext = 1;
          }
        }

        if($allowed_ext==1)
        {
          $errors .= "<li>The uploaded file is not supported file type</li>";
          // " Only the following file types are supported: ".implode(',',$allowed_extensions);
        }

       // Check for Errors
       if(strlen($error_message) > 0) { // Check length of error message
          $errors=1; // There are Errors
       }    

1 个答案:

答案 0 :(得分:1)

Simply use in_array(), replace your code with new one

// your code to be replaced    
//------ Validate the file extension -----

    $allowed_ext = 0;
    for($i=0; $i<sizeof($allowed_extensions); $i++)
    {
      if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
      {
        $allowed_ext = 1;
      }
    }

    if($allowed_ext==1)
    {
      $errors .= "<li>The uploaded file is not supported file type</li>";
      // " Only the following file types are supported: ".implode(',',$allowed_extensions);
    }


// new code
//------  Validate the file extension -----

if(!in_array($type_of_uploaded_file,$allowed_extensions))
{
    $errors .= "<li>The uploaded file is not supported file type</li>";         
}