填满的$ _FILES不返回文件扩展名

时间:2018-11-22 00:00:25

标签: php arrays file loops

我基于Stackoverflow的一个旧主题,编写了一个简短的脚本来上传多个文件:How do you loop through $_FILES array? (因为它已经7岁了,所以我没有回信。如果我做错了,请告诉我)

if(!empty($_FILES)) {
    $i = 0;
    foreach($_FILES['images']['tmp_name'] as $index => $tmpName) {
        if(!empty($tmpName) && is_uploaded_file($tmpName)) {
            $img_url = url_rewrite($intitule).'-' . time() . $i . '.'.strtolower(substr(strrchr($tmpName, '.'),1));
            $gallery = $gallery . '|' . $img_url;
            move_uploaded_file( $tmpName, $dir_upload . '/' . $img_url);
        }
        $i++;
    }
 }
 echo $gallery;

所以基本上,我要在$ _FILES ['images']中发送多个文件,并在上传之前创建唯一的名称(使用time()+ $ i)。我从未得到文件扩展名,因为$ _FILES ['images'] ['name']似乎为空。并非如此,因为Var_dump返回了包含我需要的所有内容的完整数组:

array(1) {
  ["images"]=> array(5) { 
    ["name"]=> array(5) { 
      [0]=> string(13) "my-file-1.jpg" 
      [1]=> string(13) "my-file-2.jpg" 
      [2]=> string(13) "my-file-3.jpg" 
      [3]=> string(13) "my-file-4.jpg" 
      [4]=> string(13) "my-file-5.jpg" 
    }
    ["type"]=> array(5) { 
      [0]=> string(10) "image/jpeg" 
      [1]=> string(10) "image/jpeg" 
      [2]=> string(10) "image/jpeg" 
      [3]=> string(10) "image/jpeg" 
      [4]=> string(10) "image/jpeg" 
    }
    ["tmp_name"]=> array(5) { 
      [0]=> string(14) "/tmp/php1Nrgb4" 
      [1]=> string(14) "/tmp/phpnIJHZa" 
      [2]=> string(14) "/tmp/phpcAEf1c" 
      [3]=> string(14) "/tmp/phpbHgrVj" 
      [4]=> string(14) "/tmp/phpGu0FIp" 
    } 
    ["error"]=> array(5) { 
      [0]=> int(0) 
      [1]=> int(0) 
      [2]=> int(0) 
      [3]=> int(0) 
      [4]=> int(0) 
    } 
    ["size"]=> array(5) { 
      [0]=> int(262684) 
      [1]=> int(15644) 
      [2]=> int(32638) 
      [3]=> int(11897) 
      [4]=> int(103303) 
    }
  }
}

我还需要['type']来测试文件,但是同样的事情:我无法返回数组的内容。

您在此脚本中看到错误了吗?

1 个答案:

答案 0 :(得分:3)

$_FILES['images']['tmp_name']不包含扩展名,即由上载文件组成的临时文件PHP。

如果要使用从用户PC上载的文件扩展名的文件名,则需要查看$_FILES['images']['name']

所以

foreach($_FILES['images']['tmp_name'] as $index => $tmpName) {
    if(!empty($tmpName) && is_uploaded_file($tmpName)) {
        $img_url = url_rewrite($intitule)
                    .'-' 
                    . time()
                    . $i 
                    . '.'
                    . strtolower(substr(strrchr($_FILES['images']['name'][$index], '.'),1));
                    // changed here -----------------------------^^^^^^^^^^^^^^^^
        $gallery = $gallery . '|' . $img_url;
        move_uploaded_file( $tmpName, $dir_upload . '/' . $img_url);
    }
    $i++;
}

您还可以简化获得扩展名的那一系列功能

        $img_url = url_rewrite($intitule)
                    .'-' 
                    . time()
                    . $i 
                    . '.'
                    . pathinfo($_FILES['images']['name'][$index], PATHINFO_EXTENSION);

        $gallery = $gallery . '|' . $img_url;