如何让用户在 PHP 中上传具有特定扩展名的多个文件?

How to let users upload multiple files with specific extensions in PHP?

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

例如,用户可以上传他们想要的任何文件(.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

  }
}

试试这个

$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" />

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

$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

    }
}