2012-05-09 176 views
0

請參閱下面的代碼片段。我以一種限制5 MB以上文件的方式使用它。每當文件大於5 MB時它就會提示「您嘗試上傳的文件不被允許」,實際上它應該會顯示「您嘗試上傳的文件太大」。這並不是說我把他們的代碼中的錯誤部分,我使用:如何限制上傳文件大小?

if(filesize($_FILES['filename']['tmp_name']) > $max_filesize) 

整個代碼:

// Configuration - Your Options 
$allowed_filetypes = array('.pdf','.jpg','.png','.gif'); 
$max_filesize = 5242880; // Maximum filesize in BYTES (currently 0.5MB). 
$upload_path = "/store/user/$user"; 
$filename = $_FILES['filename']['name']; 
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); 
if(!in_array($ext,$allowed_filetypes)) 
die('The file you attempted to upload is not allowed.'); 
// Now check the filesize, if it is too large then DIE and inform the user. 
if(filesize($_FILES['filename']['tmp_name']) > $max_filesize) 
die('The file you attempted to upload is too large.'); 
// Check if we can upload to the specified path, if not DIE and inform the user. 
if(!is_writable($upload_path)) 
die(''); 
+0

上傳一個_less_然後是.5MB的文件會發生什麼? – JakeParis

+0

最好的方法應該是檢查客戶端文件的大小(但我不知道如何,從谷歌一些js :-))。在服務器端,你可以簡單地設置限制ini_set/upload_max_filesize並檢查錯誤... – Fanda

+0

@Fanda,我敢肯定,嘗試限制'ini_set'的上傳大小不能很好地工作。 – JakeParis

回答

1

你的文件擴展名的代碼是不正確的,最有可能的。

嘗試用:

$allowed_filetypes = array('pdf', 'jpg', 'png', 'gif'); 
// ... 
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); 
// ... 

否則,該文件基本上不會由於文件大小限制上傳;你可以查看$_FILES['filename']['error']來查看。該值應爲0

如果不是0,您可以在這裏查看這意味着什麼:http://www.php.net/manual/en/features.file-upload.errors.php

在你的情況下,該文件可能是太大;請在此處檢查可能出現的錯誤:http://www.php.net/manual/en/features.file-upload.common-pitfalls.php

+0

嘗試過但是同樣的事 – ariel

+0

然後我建議你做一個'var_dump($ ext,$ allowed_filetypes);'並顯示結果。 –

+0

bool (false)array(4){[0] => string(4)「.pdf」[1] => string(4)「.jpg」[2] => string(4)「.png」[3] => string(4)「.gif」}你試圖上傳的文件是不允許的 – ariel

相關問題