[php] Check file size before upload

I am using this javascript that I got from here, and it works perfectly for what I need it to.

var _validFileExtensions = [".jpg", ".jpeg"]; 

function File_Validator(theForm){
    var arrInputs = theForm.getElementsByTagName("input"); 
    for (var i = 0; i < arrInputs.length; i++) { 
    var oInput = arrInputs[i]; 
    if (oInput.type == "file") { 
        var sFileName = oInput.value; 
        var blnValid = false; 
            for (var j = 0; j < _validFileExtensions.length; j++) { 
                var sCurExtension = _validFileExtensions[j]; 
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) { 
                    blnValid = true; 
                    break; 
                    } 
                } 

                if (!blnValid) { 
                    alert("Invalid image file type!"); 
                    return false; 
                } 
        } 
    } 

return true; 
} 

Now, I was wondering if, in addition, I could check the file size and fail if the file is bigger than 500kb -> all before pressing the submit/upload button?

EDIT

After looking into what PHPMyCoder suggested, I end up solving by using this javascript code:

<script language='JavaScript'>
function checkFileSize(inputFile) {
var max =  3 * 512 * 512; // 786MB

if (inputFile.files && inputFile.files[0].size > max) {
    alert("File too large."); // Do your thing to handle the error.
    inputFile.value = null; // Clear the field.
   }
}
</script>

This checks the file size, and alert the user before submitting the form.

This question is related to php javascript file-upload image-uploading filesize

The answer is


I created a jQuery version of PhpMyCoder's answer:

$('form').submit(function( e ) {    
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});

function get_extension(filename) {
    return filename.split('.').pop().toLowerCase();
}

JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.


Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to image-uploading

How to store images in mysql database using php Multiple Image Upload PHP form with one input Uploading Images to Server android How to upload images into MySQL database using PHP code Check file size before upload ios Upload Image and Text using HTTP POST Send file via cURL from form POST in PHP What is the best place for storing uploaded images, SQL database or disk file system?

Examples related to filesize

Check file size before upload Converting file size in bytes to human-readable string How to get the size of a file in MB (Megabytes)? Find size of Git repository PHP post_max_size overrides upload_max_filesize Get file size before uploading How can I get a file's size in C++? PHP filesize MB/KB conversion Better way to convert file sizes in Python Using C++ filestreams (fstream), how can you determine the size of a file?