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

时间:2015-01-04 21:37:53

标签: php image file-upload upload

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

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

  }
}

2 个答案:

答案 0 :(得分:0)

试试这个

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

答案 1 :(得分:0)

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

$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

    }
}