Server side file validation - php

I'm trying to make file upload to server by form:
<form action="send_valid.php" method="POST" enctype= "multipart/form-data">
<br>
<input type="file" name="pdf" id="pdf" accept="application/pdf"/>
<input type="hidden" name="MAX_FILE_SIZE" value="10000000"/>
<input type="submit" value="Wyƛlij">
</form>
and I want to allow user to send only pdf files of a max size 10Mb.
My php configuration for uploads is:
file_uploads = On
upload_tmp_dir = "E:\Xampp\tmp"
upload_max_filesize = 11M
max_file_uploads = 20
post_max_size = 12M
To check file size I use:
if($_SERVER["REQUEST_METHOD"] == "POST"){
var_dump($_FILES);
if(extract($_FILES)){
if($pdf['size']>10000000){
echo "File size is too large!";
}
}
Now I want to show user an error (for now) with echo when file is too big. It works fine if it is lower than 10Mb (even the code above works when I change size to 1Mb and file is larger then it will display echo), but for files of 10Mb and above it produces that error:
Warning: POST Content-Length of 11450416 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
array(0) { }
I don't have any clue why it shows it exceeds 8Mb since in configs I couldn't find 8Mb anywhere.
Where can be the problem? Is there a way to catch an upload that exceeds configuration setting to not show user the php server error?
And if I want to make file validation does above method and checking file extension with for examle:
$ext = pathinfo($_POST['pdf'], PATHINFO_EXTENSION);
is it enough? Any insight on file validation would be really helpful.

Probably this
ini_set('post_max_size', '512M');
ini_set('upload_max_filesize', '512M');
Change 512 to any of you want.

Update the values of post_max_size and upload_max_filesize in your php configuration file.
Note that the values are measured in bytes.
Reference
http://php.net/manual/en/ini.core.php#ini.post-max-size
http://php.net/manual/en/ini.core.php#ini.upload-max-filesize

Put this code before move_uploaded_file function
if($_FILES['pdf']['size']>10000000) {
exit("File size is too large!");
}
Thanks

Related

Force efficient small file upload for IE9/PHP/jQuery

I want to have a small upload limit (e.g. 100 kb for testing, perhaps 6 Mb ultimately). The size of the upload can be checked:
before the upload
fail when too much is uploaded
after the upload
If the user is trying a 1 Gb file ideally (1) should happen so that the file isn't uploaded at all. If not, (2) should happen so that it doesn't take long before the user knows the file is too big. I'd like to avoid the other possibility (3).
In HTML5 but not in IE9 the filesize can be checked before uploading using:
this.files[0].size
Get file size before uploading
In IE9 the following might work if the security settings are adjusted:
var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
Ideally I'd like to use a method that works with IE9. I've heard about flash files being used. I'd like a method that is separate - not using a big plugin.
Here is my code. At the moment it uploads the whole file before it checks if the file size is too big.
<?php
if (isset($_FILES['myfile'])) {
if ($_FILES['myfile']['error'] == UPLOAD_ERR_FORM_SIZE) {
// $_FILES['myfile']['size'] is 0
echo 'Error: file is too big!<br>';
}
else if ($_FILES['myfile']['size'] > 100000) {
echo 'File size is too big!<br>';
}
else {
echo 'File uploaded ok.<br>';
}
}
var_dump($_FILES);
?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="file" name="myfile" />
<input type="submit" value="Submit" />
</form>
The small upload limit is just for one form so I don't want to change the global PHP settings file.
I'm not sure using MAX_FILE_SIZE is a good idea - the person still has to upload the entire file and the filesize data is lost (I might want to tell people how big their upload was)
ini_get('post_max_size') returns 8M and ini_get('upload_max_filesize') returns 32M. If files that are over 8 Mb try to be uploaded the file is still fully uploaded (even 40+ Mb). After larger than 8 Mb files are uploaded var_dump($_FILES) returns an empty array.
If the file is bigger than about 600 Mb I get a 413 error... that is (1).
So I want to do (1) or (2) in IE9, PHP and jQuery.

PHP file upload (3.5 MB) upload

I trying to use file input to upload a 3.5MB file, but when I try to upload it, I get a $_FILES['error'] == 2, I believe that is telling me that the file is way too big.
what can I do to get this to upload?
here is some of my code:
<input type="hidden" name="MAX_FILE_SIZE" value="100000000000000000000000000000000000000000000000000000000000000">
<input type="file" id="home_pdf" name="home_pdf">
my php settings are the following:
post_max_size = 128M
memory_limit = 128M
max_file_uploads = 20
max_execution_time = 30
upload_max_filesize = 128M
100000000000000000000000000000000000000000000000000000000000000 is too big of a number, and overflows. Try 134217728 instead (128MB).
PHP has a maximum int value of 9,223,372,036,854,775,807 on 64 bit installations and 2,147,483,647 on 32-bit installations.
I've tested this and can reproduce your issue and it gets fixed by lowering the value.
See POST method uploads
The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.
Your MAX_FILE_SIZE field is too big.
from the PHP manual:
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
According to docs:
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
You should check the MAX_FILE_SIZE directive that was specified in the HTML form.
Also, as noted from #BrandonWamboldt, you have specified an invalid attribute value for the MAX_FILE_SIZE directive.
It may sound silly, but sometimes it is necessary in upload script to add a setting for php_ini. Example:
ini_set("max_execution_time", 120);
ini_set("max_input_time", 120);
ini_set("memory_limit", "128M");
ini_set("upload_max_filesize", "10M");
ini_set("post_max_size", "10M");
For some reason this works. I had a similar problem and that was my solution.
My opinion for name MAX_FILE_SIZE and value 100000000000000000000000000000000000000000000000000000000000000 is realy bad move and not recommended to be visible. That part define in PHP upload function and reduce the number of zeros (the value is tooooooooo large).

Laravel 4.x :Validation input file doesn't work

Hey everyones: I've got a problem here! I'm doing my project using laravel framework. I've got a problem when I try to validate an input files. I made a simple site for testing with a same problem. Here's my Route:
Route::get('test','TestController#uploadFile');
Route::post('test','TestController#uploadFile');
Here's my controller:
class TestController extends Controller{
public function uploadFile(){
return View::make('test');
}
public function pUploadFile(){
try {
$file=Input::file('file');
$validator=Validator::make(array('file' => $file ),array('file' =>'image|mimes:jpeg,jpg,png,gif|max:3072'));
if($validator->fails()){
return View::make('test')->withErrors($validator);
}
$destinationPath = "uploads";
$extension =$file->getClientOriginalExtension();
$filename='testfile'.$extension;
$upload_success = $file->move($destinationPath, $filename);
if($upload_success)
return 'succeeded';
return 'failed';
} catch (Exception $e) {
return $e;
}
}
}
And here's my blade.php file :
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<form method="post" action="{{Asset('test')}}" id="form-register" enctype="multipart/form-data">
<h2>Choose an image</h2>
<input type="file" name="file" id="file"/>
{{$errors->first('file')}}
<button>Upload</btn>
</form>
</div>
</body>
</html>
When I chose a swf file with size:66mb and push the button, I got an error:
Warning: POST Content-Length of 64859333 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
It shouldn't cross over the validation rules! Why is that? Can anyboby help me?
ps:Sorry if my english is terrible :D
Thank you very much all you guys. It works!!! But now the new problem has coming. We can't control people when they choose a large file than 'post_max_size'. lol
Your PHP configuration only allows for a maximum of 8MB to be uploaded. Adjust the post_max_size and upload_max_filesize in your php.ini.
upload_max_filesize = 128M
post_max_size = 128M
Its not validation rules problem its related to settings you have in there.
Make sure you update post_max_size and max_file_uploads in php.ini to a larger value.
max_file_uploads = 256
post_max_size= 256
You can find where is your php.ini file with phpinfo() function.
http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize
post_max_size integer
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. If memory limit is enabled by your configure
script, memory_limit also affects file uploading. Generally speaking,
memory_limit should be larger than post_max_size. When an integer is
used, the value is measured in bytes. Shorthand notation, as described
in this FAQ, may also be used. If the size of post data is greater
than post_max_size, the $_POST and $_FILES superglobals are empty.
This can be tracked in various ways, e.g. by passing the $_GET
variable to the script processing the data, i.e. , and then checking if
$_GET['processed'] is set.
max_file_uploads integer
The maximum number of files allowed to be uploaded simultaneously.
Starting with PHP 5.3.4, upload fields left blank on submission do not
count towards this limit.

PHP file uploading and detecting file size

I have a form that lets users upload files but I'm having problems detecting files that are too large.
I have the following set in php.ini:
upload_max_filesize = 10M
post_max_size = 20M
I understand that the standard way to detect if files are larger than the config file allows is to check $_FILES['file_name']['error']. However this only works for me if the actual file is greater than upload_max_filesize and smaller than post_max_size.
If the actual file size is greater than post_max_size then the $_FILES variable is removed and I get the log message:
PHP Warning: POST Content-Length of xxx bytes exceeds the limit of
yyy ...
So the question: How do I detect if a user is uploading a file that is greater than post_max_size? I need to display a valid user message if this happens.
Thanks.
I suggest you use set_error_handler() and check for E_USER_WARNING error + appropriate message, and then send it to a user, possibly via throwing an Exception, possibly some other way.
Like this:
$filesize = $_FILES['file']['size'];
$limit = ini_get('post_max_size');
if($filesize > $limit) {
trigger_error("POST Content-Length of $filesize bytes exceeds the limit of $limit bytes.", E_WARNING);
}
else {
// upload file
}

Check if file uploaded successfully

To start off, I've set my post_max_size in /etc/php.ini to 4M just as a test. I have a check in place to check for file type and size of file. I want to only accept JPG, GIF and PNG. The file size cannot be larger than 4M. It seems that if the file size is larger than what's set in post_max_size, my code won't throw an error. If I set my PHP to deny uploads larger than let's say 2M but less than 4M, it'll throw an error (what i want). I believe this is due to PHP not accepting anything over 4M.
if (is_uploaded_file($_FILES["file"]["tmp_name"]))
{
$file_type = exif_imagetype($_FILES["file"]["tmp_name"]);
} else {
$this->form_validation->set_message('valid_image', 'Error uploading file!!!');
return false;
}
There is another ini flag upload_max_filesize that you should increase to your new limit as well
Use the value in $_FILES["file"]["error"] to check the upload status.
Not sure, but I would check for file size on the client before the upload happens. This approach would upload the whole file to the server first before giving the error even if it worked.
($_FILES['uploaded_file']['error'] == 0)
is a successful upload.

Categories