Detect If Uploaded File Is Too Large

Detect if uploaded file is too large

You could check the $_SERVER['CONTENT_LENGTH']:

// check that post_max_size has not been reached
// convert_to_bytes is the function turn `5M` to bytes because $_SERVER['CONTENT_LENGTH'] is in bytes.
if (isset($_SERVER['CONTENT_LENGTH'])
&& (int) $_SERVER['CONTENT_LENGTH'] > convert_to_bytes(ini_get('post_max_size')))
{
// ... with your logic
throw new Exception('File too large!');
}

How to detect if a user uploaded a file larger than post_max_size?

For a simple fix that would require no server side changes, I would use the HTML5 File API to check the size of the file before uploading. If it exceeds the known limit, then cancel the upload. I believe something like this would work:

function on_submit()
{
if (document.getElementById("upload").files[0].size > 666)
{
alert("File is too big.");
return false;
}

return true;
}

<form onsubmit="return on_submit()">
<input id="upload" type="file" />
</form>

Obviously it's just a skeleton of an example, and not every browser supports this. But it wouldn't hurt to use this, as it could be implemented in such a way that it gracefully degrades into nothing for older browsers.

Of course this doesn't solve the issue, but it will at least keep a number of your users happy with minimal effort required. (And they won't even have to wait for the upload to fail.)

--

As an aside, checking $_SERVER['CONTENT_LENGTH'] vs the size of the post and file data might help detect if something failed. I think it when there is an error it will be non zero, while the $_POST and $_FILES would both be empty.

How to detect if a file upload is large than the maximum allowed

Use ini_set('post_max_size', '8M'); to set the max-post size to 8 megabytes.

Use ini_set('upload_max_filesize', '8M'); to set the individual size of files to 8 megabytes - you can still post more than 8MB if you upload multiple files, which can be desirable.

If the file is 'too big' you will still get the posted file in $_FILES but there will be an error code and the temp-file wont be there if you look for it.

$_FILES["file"]["error"] can have one of these values: http://php.net/manual/en/features.file-upload.errors.php

Typically you'll write some switch case statement to deal with error codes.

JavaScript file upload size validation

Yes, you can use the File API for this.

Here's a complete example (see comments):

document.getElementById("btnLoad").addEventListener("click", function showFileSize() {
// (Can't use `typeof FileReader === "function"` because apparently it
// comes back as "object" on some browsers. So just see if it's there
// at all.)
if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal
console.log("The file API isn't supported on this browser yet.");
return;
}

var input = document.getElementById('fileinput');
if (!input.files) { // This is VERY unlikely, browser support is near-universal
console.error("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
addPara("Please select a file before clicking 'Load'");
} else {
var file = input.files[0];
addPara("File " + file.name + " is " + file.size + " bytes in size");
}
});

function addPara(text) {
var p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
}
body {
font-family: sans-serif;
}
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load'>
</form>

Detecting file upload size on the client side?

On MAX_FILE_SIZE

Read This:

...At http://pk.php.net/manual/en/features.file-upload.post-method.php and equivalent locations in other formats, it is stated
that browsers take the value of a MAX_FILE_SIZE form field into
account.

This information is repeated elsewhere on the web and in books, but
appears to originate from the PHP documentation (it does not appear in
terms of other server-side technologies
).

There is nothing in any of the HTML, HTTP or related specs to indicate
that this is the case (in particular RFC 1867 which introduced file
uploads to HTML doesn't mention it
, so it isn't even a case of a kludge
that was mentioned in the first RFC and then dropped) nor does it make
sense in the context of the HTML specs (there is nothing to indicate any
relationship between that particular hidden input and the file input).
The only statements about hidden fields I could find in any of them was
warnings in the security considerations sections against user-agents
basing any file-related operations on anything mentioned in a hidden
field.

No browsers appear to perform this as an "extension". Indeed given that
there are potentially other possible meanings for a hidden field with
that name in an application handling several file uploads, it would have
to be considered a design flaw any any did.

I submit that there is no such mechanism in mainstream browsers (if any
at all) and indeed shouldn't be. Reference to it should be dropped from
documentation.

I'd further suggest that since this idea has propagated from this
documentation elsewhere that a note about it not working should to be
added.

If a mechanism is required or desired for more rapidly handling this
sort of file handling issue then it requires functionality to allow PHP
to intercept streams being uploaded before request completion, which
would be completely different to how this documentation suggest it
should be dealt with, even if it was true...

  • http://www.juangiordana.com.ar/blog/2007/12/08/max_file_size-erroneo/

the code below come from swfUpload php implementation:

// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
header("HTTP/1.1 500 Internal Server Error");
echo "POST exceeded maximum allowed size.";
exit(0);
}
// Validate the file size (Warning the largest files supported by this code is 2GB)
$max_file_size_in_bytes = 2147483647;
$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
if (!$file_size || $file_size > $max_file_size_in_bytes) {
HandleError("File exceeds the maximum allowed size");
exit(0);
}


Related Topics



Leave a reply



Submit