【问题标题】:How to let users upload multiple files with specific extensions in PHP?如何让用户在 PHP 中上传多个具有特定扩展名的文件?
【发布时间】:2015-01-04 21:37:52
【问题描述】:

这是我偶然发现的一段代码,它允许用户将多个文件上传到您的网站。它工作得很好,但是我如何才能使上传的文件类型受到限制?

例如,用户可以上传他们想要的任何文件(.txt、.php、.png、.jpg 等),但假设我只希望他们上传(.html、.png、.jpg),怎么会我这样做?

$target_dir = "";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);


//Loop through each file
for($i=0; $i<count($_FILES['fileToUpload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['fileToUpload']['tmp_name'][$i];

//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "" . $_FILES['fileToUpload']['name'][$i];

//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {

  //Handle other code here

  }
}

【问题讨论】:

    标签: php image file-upload upload


    【解决方案1】:

    我会创建一个允许的文件扩展名列表,然后检查上传的文件是否有效

    $target_dir = "";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    
    $allowed = array("html", "jpg", "png");
    
    //Loop through each file
    for($i=0; $i<count($_FILES['fileToUpload']['name']); $i++) {
    
        //Get the temp file path
        $tmpFilePath = $_FILES['fileToUpload']['tmp_name'][$i];
        $filename = $_FILES['fileToUpload']['name'][$i];
    
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
    
        if(!in_array($ext, $allowed)){
            continue;
        }
    
        //Make sure we have a filepath
        if ($tmpFilePath != ""){
        //Setup our new file path
        $newFilePath = "" . $_FILES['fileToUpload']['name'][$i];
    
        //Upload the file into the temp dir
        if(move_uploaded_file($tmpFilePath, $newFilePath)) {
    
            //Handle other code here
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      $file_type = $_FILES['fileToUpload']['type']; //returns the mimetype
      $allowed = array("image/png", "image/jpg");
      if(!in_array($file_type, $allowed)) {
        $error_message = 'Only jpg, gif are allowed.';
        $error = 'yes';
      }
      

      即使在表单页面中你也可以这样做

      <input type="file" name="fileToUpload" accept="image/x-png, image/jpeg" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-26
        • 1970-01-01
        • 1970-01-01
        • 2016-07-26
        • 1970-01-01
        • 2011-06-07
        • 2019-10-13
        • 1970-01-01
        相关资源
        最近更新 更多