我需要检查上传的文件是否.csv
或.txt
作为扩展,我的做法如下:
$uploadfiles = $_FILES[\'uploadfiles\'];
echo \'<pre>\';
var_dump($uploadfiles);
echo \'</pre>\';
if (is_array($uploadfiles)) {
foreach ($uploadfiles[\'name\'] as $key => $value) {
if ($uploadfiles[\'error\'][$key] == 0) {
$filetmp = $uploadfiles[\'tmp_name\'][$key];
$filename = $uploadfiles[\'name\'][$key];
$filetype = wp_check_filetype(basename($filename), null);
$filetitle = preg_replace(\'/\\.[^.]+$/\', \'\', basename($filename));
$filename = $filetitle . \'.\' . $filetype[\'ext\'];
$upload_dir = wp_upload_dir();
if ($uploadfiles[\'type\'] != "text/csv" || $uploadfiles[\'type\'] != "text/plain") {
echo "Error, the file $filename has not a valid extension: " . $filetype["ext"];
continue;
}
echo "entre";die();
$i = 0;
while (file_exists($upload_dir[\'path\'] . \'/\' . $filename)) {
$filename = $filetitle . \'_\' . $i . \'.\' . $filetype[\'ext\'];
$i++;
}
$filedest = $upload_dir[\'path\'] . \'/\' . $filename;
if (!is_writeable($upload_dir[\'path\'])) {
$this->msg_e(\'Unable to write to directory %s. Is this directory writable by the server?\');
return;
}
if (!move_uploaded_file($filetmp, $filedest)) {
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
}
}
}
但我一直在犯这样的错误:
错误,文件Aruba Airlines票券(截止2014年4月27日)-Aruba Airlines票券。csv没有有效的扩展名:csv
我还使用以下代码进行测试:
if ($filetype[\'type\'] != "text/csv" || $filetype[\'type\'] != "text/plain") {
echo "Error, the file $filename has not a valid extension: " . $filetype["ext"];
continue;
}
结果是一样的。如果我这样做:
echo \'<pre>\';
var_dump($uploadfiles);
echo \'</pre>\';
结果是:
array (size=5)
\'name\' =>
array (size=1)
0 => string \'Aruba Airlines tickets-coupons (through 27-Apr-2014) - Aruba Airlines tickets-coupons .csv\' (length=90)
\'type\' =>
array (size=1)
0 => string \'text/csv\' (length=8)
\'tmp_name\' =>
array (size=1)
0 => string \'/tmp/php53tzhZ\' (length=14)
\'error\' =>
array (size=1)
0 => int 0
\'size\' =>
array (size=1)
0 => int 14084526
那么错误在哪里呢?
Checking for compared values types
因此,根据这里一位成员的建议,我这样做了:
echo \'<pre>\';
print_r($uploadfiles);
echo \'</pre>\';
// this is the only key since I\'m uploading
// just one file for that I check in [0]
echo gettype($uploadfiles[\'type\'][0]);
// output: string
然后:
echo gettype($filetype[\'type\']);
// output: string
然后:
if ($filetype[\'type\'] != $fileCSV || $filetype[\'type\'] != $fileText) {
echo "Error, the file $filename has not a valid extension: " . $filetype["ext"];
continue;
}
还是会犯同样的错误,这让我抓狂!