php - 如何在 PHP 中限制文件上传类型的文件大小?

标签 php file file-upload

我有一个上传表单,正在检查文件大小和文件类型以将上传的文件限制为 2 兆字节以及 .pdf、.jpg、.gif 或 .png 文件类型。我的目标是在用户违反其中一条规则时向他们显示警告消息。

有四种情况:

  1. 正确的尺寸/正确的类型(工作)
  2. 正确的尺寸/不正确的类型(工作)
  3. 不正确的尺寸/正确的类型(不工作)
  4. 尺寸不正确/类型不正确(无效)

使用我当前的代码,当文件大小大于 2 兆字节时 (#4),它总是显示不正确的“类型”消息,即使文件类型是正确的 (#3)。

有什么想法吗?

if (isset ( $_FILES['uploaded_file'] ) ) {

    $file_size = $_FILES['uploaded_file']['size'];
    $file_type = $_FILES['uploaded_file']['type'];

    if (($file_size > 2097152)){      
        $message = 'File too large. File must be less than 2 megabytes.'; 
        echo '<script type="text/javascript">alert("'.$message.'");</script>'; 
    }
    elseif (  
        ($file_type != "application/pdf") &&
        ($file_type != "image/jpeg") &&
        ($file_type != "image/jpg") &&
        ($file_type != "image/gif") &&
        ($file_type != "image/png")    
    ){
        $message = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.'; 
        echo '<script type="text/javascript">alert("'.$message.'");</script>';         
    }    
    else {
        store_uploaded_file($id);
    }

}   

最佳答案

您的代码没有考虑到的是显示多个错误。正如您在上面提到的,用户可能会上传一个大于 2MB 的错误类型的文件,但您的代码只能报告其中一个问题。尝试类似的东西:

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

查看 move_uploaded_file() 的文档(这叫做移动而不是存储)更多。

关于php - 如何在 PHP 中限制文件上传类型的文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9153224/

相关文章:

c - 如何计算文件中每个数字的出现频率?

file-upload - 如何仅为一个可恢复上传的视频获取YouTube访问 token

java - 公共(public)文件上传(Apache)

php - Symfony 2 网络套接字

python - 通过文件名通配符打开文件

php - 从 5.2.x 更新的 PHP 5.3.6 上的 PDO 错误

python - Django动态文件上传路径

javascript - nodejs 在文件上传时抛出 ENOENT 错误

php - 通过 (f|v|s)scanf 函数读取 PHP_INT_MAX 或接近值

php - json_decode 当值为空时返回 null