How to limit file upload type file size in PHP?

142,153

Solution 1

Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

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
    }
}

Look into the docs for move_uploaded_file() (it's called move not store) for more.

Solution 2

Hope this helps :-)

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.";
    }
}

Solution 3

If you are looking for a hard limit across all uploads on the site, you can limit these in php.ini by setting the following:

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

that will set the maximum upload limit to 2 MB

Solution 4

Hope This useful...

form:

<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";
                }
            }
    }
?>
Share:
142,153

Related videos on Youtube

Michael
Author by

Michael

Updated on September 17, 2020

Comments

  • Michael
    Michael over 3 years

    I have an upload form and am checking the file size and file type to limit the uploaded file to 2 megabytes and either .pdf, .jpg, .gif or .png file types. My goal is to have an alert message displayed to the user if they violate one of these rules.

    There are four scenarios:

    1. Correct Size / Correct Type (working)
    2. Correct Size / INCORRECT Type (working)
    3. INCORRECT Size / Correct Type (not working)
    4. INCORRECT Size / INCORRECT Type (not working)

    With my current code, it always displays the incorrect "type" message when the file size is greater than 2 megabytes (#4), even if the file type is correct (#3).

    Any ideas why?

    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);
        }
    
    }   
    
    • Michael
      Michael over 12 years
      sorry, that wasn't an accurate representation. the alert is not called if they file is actually uploaded. updated question.
    • Bailey Parker
      Bailey Parker over 12 years
      Are you die()ing or exit()ing after the header() or does your code end after that if statement?
    • Michael
      Michael over 12 years
      sorry, i'm trying to summarize. it calls the the store_uploaded_file() function, which performs other actions on the page. the code does not end after the successful upload.
    • dar7yl
      dar7yl over 12 years
      you could dump the _FILES structure to see what exactly is being sent: <?php echo "<!-- _FILES: "; print_r($_FILES); echo " -->\n"; Note: different browsers may send different information.
  • Bailey Parker
    Bailey Parker over 12 years
    Although this is not very portable across some hosts (which don't allow PHP.ini modification) or if you wanted to impose different file size limits on another php file.
  • Michael
    Michael over 12 years
    Your code is much cleaner; however, I discovered that my issue was actually with the limit set in php5.ini. I am using GoDaddy, which defaults the limit to 2MB. For all files uploaded that are larger than this, the return value of $_FILES['uploaded_file']['size'] comes back as "0" and the return value of $_FILES['uploaded_file']['type'] is empty. I had to modify your code a bit.
  • Dharmang
    Dharmang almost 11 years
    hi, I think if(count($errors) !== 0) should be if(count($errors) == 0), though it is not a logical mistake, kind of typo error, but I think it should be corrected to avoid any confusion.
  • Gogol
    Gogol over 8 years
    By the way, your code is vulnerable to RFI. Client can modify the type attribute during upload. Better check for extensions instead of/along with type. For a cleaner example, $whitelist = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'txt', 'rtf', 'odt'];$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); if (in_array($extension,$whitelist)){ /* do your stuff */} ( might not look clean in the comment loool :P )
  • J Ramesh Fernandez
    J Ramesh Fernandez over 8 years
    @PhpMyCoder What if i upload a file, which is larger than upload_max_filesize in php.ini? No errors were shown in that case. file is also not uploaded.
  • Dorian Fabre
    Dorian Fabre about 7 years
    Shouldn't the line if(!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) { actually be if(!in_array($_FILES['uploaded_file']['type'], $acceptable)) || (empty($_FILES["uploaded_file"]["type"]))) { ? At the moment it's reading "if the file type is not in the array AND there is a file type..." rather than "if the file type is not in the array OR there is no file type...". In the first instance the part after the AND is redundant.
  • Tog Porter
    Tog Porter almost 7 years
    There is an open bracket missing - should be: if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) || (empty($_FILES["uploaded_file"]["type"]))) {