如何限制上传文件大小?

时间:2012-05-09 01:39:22

标签: php file upload filesize

请参阅下面的代码段。我正在使用它来限制超过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('');

1 个答案:

答案 0 :(得分: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