How to Limit File Upload Type File Size in PHP

How to limit file upload type file size in PHP?

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.

How to limit file upload size on form submission in php

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

limit file size for jpg and pdf uploads

If you want to limit all the resources replace:

if ( $is_image && $size > $limit ) {
$file['error'] = 'Image files must be smaller than ' . $limit_output;
}//end if

with:

if ( $size > $limit ) {
$file['error'] = 'Files must be smaller than ' . $limit_output;
}//end if

Optional [1]: you can rename the max_image_size function to max_file_size and change the addfilter to add_filter( 'wp_handle_upload_prefilter', 'max_file_size' );

Optional [2]: you can detect the PDF mime type, which is application/pdf by using:

$is_pdf = strpos( $type, 'pdf' ) !== false;

and add other condition:

if ( $is_image && $size > $limit ) {
$file['error'] = 'Image files must be smaller than ' . $limit_output;
}//end if
if ( $is_pdf && $size > $limit ) {
$file['error'] = 'PDF files must be smaller than ' . $limit_output;
}//end if

php file upload, how to restrict file upload type

The below just uses the mime types to validate a file, then checks the size of both. For a list of most mime types see here or google.

function allowed_file(){

//Add the allowed mime-type files to an 'allowed' array
$allowed = array('application/doc', 'application/pdf', 'another/type');

//Check uploaded file type is in the above array (therefore valid)
if(in_array($_FILES['resume']['type'], $allowed) AND in_array($_FILES['reference']['type'], $allowed)){

//If filetypes allowed types are found, continue to check filesize:

if($_FILES["resume"]["size"] < 400000 AND $_FILES["reference"]["size"] < 400000 ){

//if both files are below given size limit, allow upload
//Begin filemove here....

}

}

}

Files not uploading despite not reaching the file size limit

The error you're getting is related to POST data in general (which uploads go through), and is not specific to file uploads.

The PHP setting you're looking for is post-max-size. You should be able to fix your issue by increasing its value.

Relevant part from the docs:

Sets max size of post data allowed. This setting also affects file
upload. To upload large files, this value must be larger than
upload_max_filesize.

Limit the size of a file upload (html input element)

This is completely possible. Use Javascript.

I use jQuery to select the input element. I have it set up with an onChange event.

$("#aFile_upload").on("change", function (e) {

var count=1;
var files = e.currentTarget.files; // puts all files into an array

// call them as such; files[0].size will get you the file size of the 0th file
for (var x in files) {

var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB

if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {

if (count > 1) {

approvedHTML += ", "+files[x].name;
}
else {

approvedHTML += files[x].name;
}

count++;
}
}
$("#approvedFiles").val(approvedHTML);

});

The code above saves all the file names that I deem worthy of persisting to the submission page before the submission actually happens. I add the "approved" files to an input element's val using jQuery so a form submit will send the names of the files I want to save. All the files will be submitted, however, now on the server-side, we do have to filter these out. I haven't written any code for that yet but use your imagination. I assume one can accomplish this by a for loop and matching the names sent over from the input field and matching them to the $_FILES (PHP Superglobal, sorry I don't know ruby file variable) variable.

My point is you can do checks for files before submission. I do this and then output it to the user before he/she submits the form, to let them know what they are uploading to my site. Anything that doesn't meet the criteria does not get displayed back to the user and therefore they should know, that the files that are too large won't be saved. This should work on all browsers because I'm not using the FormData object.

Limit file format when using input type=file ?

Strictly speaking, the answer is no. A developer cannot prevent a user from uploading files of any type or extension.

But still, the accept attribute of <input type = "file"> can help to provide a filter in the file select dialog box provided by the user's browser/OS. For example,

<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) --> 
<input type="file" accept=".xls,.xlsx" />


Related Topics



Leave a reply



Submit