How to limit file upload size on form submission in php

Viewed 1546

I have a form where I want to allow files equal or less than 50 MB. but when I upload a file of 1.60 MB it says max file size please upload less. any suggestions why?

the file size 1.60 MB and If I print file array it shows size = 1686220

// Attempt 1

if (!filesize($file_path) < 50000) {
  // max file size limit reached
}

// Attempt 2

if (!$file['size'] < 50000) {
  // max file size limit reached
}
1 Answers

you can do it using jquery before submit as well for sample:

    <form action="upload" enctype="multipart/form-data" method="post">

        Upload image:
        <input id="image-file" type="file" name="file" />
        <input type="submit" value="Upload" />

        <script type="text/javascript">
            $('#image-file').bind('change', function() {
                alert('This file size is: ' + this.files[0].size/1024/1024 + "MB");
            });
        </script>

    </form>

using PHP:

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

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

    if (($file_size > 50*1024*1024)){      
        $message = 'File too large. File must be less than 50 MB.'; 
        echo '<script type="text/javascript">alert("'.$message.'");</script>'; 
    }
}
Related