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

时间:2012-02-05 21:32:45

标签: php file file-upload

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

有四种情况:

  1. 正确尺寸/正确类型(工作)
  2. 正确尺寸/不正确类型(工作)
  3. 不正确的尺寸/正确类型(不工作
  4. INCORRECT尺寸/不正确类型(不工作
  5. 使用我当前的代码,当文件大小大于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);
        }
    
    }   
    

5 个答案:

答案 0 :(得分:35)

您的代码未考虑的内容是显示多个错误。如上所述,用户可以上传> 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()的文档(它被称为move not store)以获取更多信息。

答案 1 :(得分:4)

希望这会有所帮助: - )

if(isset($_POST['submit'])){
    ini_set("post_max_size", "30M");
    ini_set("upload_max_filesize", "30M");
    ini_set("memory_limit", "20000M"); 
    $fileName='product_demo.png';

    if($_FILES['imgproduct']['size'] > 0 && 
            (($_FILES["imgproduct"]["type"] == "image/gif") || 
                ($_FILES["imgproduct"]["type"] == "image/jpeg")|| 
                ($_FILES["imgproduct"]["type"] == "image/pjpeg") || 
                ($_FILES["imgproduct"]["type"] == "image/png") &&
                ($_FILES["imgproduct"]["size"] < 2097152))){

        if ($_FILES["imgproduct"]["error"] > 0){
            echo "Return Code: " . $_FILES["imgproduct"]["error"] . "<br />";
        } else {    
            $rnd=rand(100,999);
            $rnd=$rnd."_";
            $fileName = $rnd.trim($_FILES['imgproduct']['name']);
            $tmpName  = $_FILES['imgproduct']['tmp_name'];
            $fileSize = $_FILES['imgproduct']['size'];
            $fileType = $_FILES['imgproduct']['type'];  
            $target = "upload/";
            echo $target = $target .$rnd. basename( $_FILES['imgproduct']['name']) ; 
            move_uploaded_file($_FILES['imgproduct']['tmp_name'], $target);
        }
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
}

答案 2 :(得分:2)

如果您正在寻找网站上所有上传的硬限制,您可以通过设置以下内容在php.ini中限制这些限制:

`upload_max_filesize = 2M` `post_max_size = 2M`

将最大上传限制设置为2 MB

答案 3 :(得分:1)

希望这很有用......

形式:

<form action="check.php" method="post" enctype="multipart/form-data">
<label>Upload An Image</label>
<input type="file" name="file_upload" />
<input type="submit" name="upload"/>
</form>

check.php:

<?php 
    if(isset($_POST['upload'])){
        $maxsize=2097152;
        $format=array('image/jpeg');
    if($_FILES['file_upload']['size']>=$maxsize){
        $error_1='File Size too large';
        echo '<script>alert("'.$error_1.'")</script>';
    }
    elseif($_FILES['file_upload']['size']==0){
        $error_2='Invalid File';
        echo '<script>alert("'.$error_2.'")</script>';
    }
    elseif(!in_array($_FILES['file_upload']['type'],$format)){
        $error_3='Format Not Supported.Only .jpeg files are accepted';
        echo '<script>alert("'.$error_3.'")</script>';
        }

        else{
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
            if(move_uploaded_file($_FILES["file_upload"]["tmp_name"], $target_file)){ 
            echo "The file ". basename($_FILES["file_upload"]["name"]). " has been uploaded.";
            }
            else{
                echo "sorry";
                }
            }
    }
?>

答案 4 :(得分:0)

var sizef = document.getElementById('input-file-id').files[0].size;
                if(sizef > 210000){
                    alert('sorry error');
                }else {
                    //action
                }