【问题标题】:If statement to filter file extensions过滤文件扩展名的 if 语句
【发布时间】:2017-09-27 17:31:17
【问题描述】:

我正在创建一个允许用户上传图像的脚本,但现在我想包含一个简单的 if 语句,它只接受 gif 和 png 。这是我的代码,但它似乎没有按照它必须的方式工作。

#extention filter
$allowed = array("image/gif","image/png");  
if(!in_array($files,$allowed)){
 $error_message = 'Only jpg, gif, and pdf files are allowed.';
  $error = 'yes';
  echo $error_message;
  exit();
}   #extention

【问题讨论】:

    标签: php


    【解决方案1】:
        $filename=$_FILE['name']['filename_in_html'];  //you can change this with your filename
        $allowed='png,jpg';  //which file types are allowed seperated by comma
    
        $extension_allowed=  explode(',', $allowed);
        $file_extension=  pathinfo($filename, PATHINFO_EXTENSION);
        if(array_search($file_extension, $extension_allowed))
        {
            echo "$extension_allowed allowed for uploading file";
        }
        else
        {
            echo "$extension_allowed is not allowed for uploading file";
        }
    

    【讨论】:

      【解决方案2】:
      $file_type = $_FILES['name']['type']; //returns the mimetype
      
      $allowed = array("image/png", "image/gif", "application/pdf");
      if(!in_array($file_type, $allowed)) {
        $error_message = 'Only png, gif files are allowed.';
        $error = 'yes';
      }
      

      希望它可以帮助解决问题。

      【讨论】:

        【解决方案3】:
        $path_parts = pathinfo('/path/emptyextension.');
        var_dump($path_parts['extension']);
        

        这将返回确切的扩展名,您可以根据需要进行比较。

        【讨论】:

          猜你喜欢
          • 2021-09-05
          • 2011-04-02
          • 1970-01-01
          • 2010-12-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多