PHP Upload Test

$_FILES[«file»][«size»] returning 0?

I am trying to upload something using PHP and set a limit on the total size that I allow to be uploaded. I want to limit my uploads to 2MB but for some reason whenever I try to check with an if statement like this:

A file that is large (such as a 7mb file) will pass through the if statement because for whatever reason if I print $_FILES[«file»][«size»] , it will return 0, instead of the proper number of bytes. If I try to upload something that is smaller, like 342kb the $_FILES[«file»][«size»] will return the proper size. Is there anyway to get $_FILES[«file»][«size»] to actually hold the proper size of the file? Otherwise I do not know how to fix this problem.

Which is the limit of uploadable data in your php.ini? Are you sure that file you tried to upload (7MB) has really been uploaded correctly? I think it’s not.

I’m not 100% sure, but the max upload size of a file is set by php.ini, the php config file. If the file is larger than that limit, it will never even be uploaded to begin with, which is why you would get a file size of 0.

You are right, the 7mb file is not uploaded correctly. I get a return code 1 because php.ini has a limit of 2MB. That is why I am trying to write the if statement, but the if statement does not work. EDIT: For some reason, a file that is larger than 2MB will actually make the connection and begin to upload, it just fails after it uploads the file.

4 Answers 4

A file which aborts for any reason (upload failed, exceeds limits, etc. ) will show as size 0

You have to check for upload SUCCESS before you do ANYTHING with the rest of th eupload data:

if(array_key_exists('file', $_FILES)) < if ($_FILES['file']['error'] === UPLOAD_ERR_OK) < echo 'upload was successful'; >else < die("Upload failed with error code " . $_FILES['file']['error']); >> 

The error codes are defined here. In your case, if you’ve hardcoded a 2meg limit and someone uploads a 2.1 meg file, then the error code would be UPLOAD_ERR_INI_SIZE (aka 2 ), which is «exceeds limit set in .ini file».

It really just depends on how you want your application to react because you can have a case such as described earlier by @Deji where error code and size would return 0. I think one example of this happening is if you open a zipped file in Windows Explorer and try drag and dropping a file from the file list presented to you to certain javascript file uploaders

if( $_FILES['file']['size'] && $_FILES['file']['size'] < (2<<20)) 

very nice way, although you could've explain the code - not everyone knows how to use binary shift to do power calculations

Читайте также:  Kotlin разница во времени

How I supposed in my previous comment, your problem is that limit of uploadable file in php.ini is less than 7MB.
So you could try to use

if ($_FILES["file"]["size"] > 0 && $_FILES["file"]["size"] < 2097152) 

Consider that if you put your limit (in php.ini) to 2MB, that check could be easily written as

check for any errors prior to uploading. These will often give away what the problem is. Create a class to return any code error and use it for uploading files.

 class UploadException extends Exception < public function __construct($code) < $message = $this->codeToMessage($code); parent::__construct($message, $code); > private function codeToMessage($code) < switch ($code) < case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini."; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; break; >return $message; > > 

Now check whether the upload was success before you do anything with the file. If it's NOT uploaded successfully, it'll result in a error which will tell you what's wrong.

This way, instead of having to waste your time on guessing what the error code could mean or having to look it up all the time, your own made up error message will return the message corresponding with the error code.

 if ($_FILES['realFile']['error'] === UPLOAD_ERR_OK) < echo 'no problems encountered. File was uploaded with success'; >else

Источник

Detect if uploaded file is too large

$_FILES is not set if the file is larger then 5M. But this is a bit strange. How would you do that? EDIT: var_dump of file over 5M:

array(1) < ["fileupload"]=>array(5) < ["name"]=>string(13) "netzerk12.pdf" ["type"]=> string(15) "application/pdf" ["tmp_name"]=> string(22) "/tmp/uploads/phpWhm8M0" ["error"]=> int(0) ["size"]=> int(352361) > > 

Like @Rob said, UPLOAD_ERR_INI_SIZE error should be thrown. php.net/manual/en/features.file-upload.errors.php

@Glavić this is a good point but didn't helps either. Like I said $_FILES is not set at that point. $_FILES['fileupload']['error'] is not present.

4 Answers 4

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!'); >

Great answer, you'll probably want to replace convert_to_bytes(ini_get('post_max_size') with whatever makes sense for the situation. $_SERVER['CONTENT_LENGTH'] returns bytes.

Читайте также:  Страничка отображается как html

Like Rob mentioned, your post_max_size should be greater than your upload_max_filesize .

After that you can check $_FILES['fileupload']['error'] if it is UPLOAD_ERR_INI_SIZE the uploaded file is to large.

; Maximum allowed size for uploaded files. upload_max_filesize = 5M ; Must be greater than or equal to upload_max_filesize post_max_size = 10M 
if($_FILES['fileupload']['error'] === UPLOAD_ERR_INI_SIZE) < // Handle the error echo 'Your file is too large.'; die(); >// check for the other possible errors // http://php.net/manual/features.file-upload.errors.php 

So I have to set post_max_size to 9petabytes? If I set is to 100M for example then people start to upload 101M files and this doesn't work anymore. Yes I reconstructed it. upload_max_filesize = 5M post_max_size = 6M. If I upload 6.4M file $_FILES remains empty.

If you want to allow unlimited uploads, yes. But I would set it to a sane number. And if your $_FILES array is empty, than the file was to large. You can check for $_FILES['fileupload']['error'] === UPLOAD_ERR_NO_FILE to check if there was no file uploaded at all.

I had the same problem, where $_FILES would be empty if the uploaded file is too large. Based on the solutions of xdazz and Florian, I concluded that:

  • If the file size is greater than post_max_size , then $_FILES is empty and $_FILES['fileupload']['error'] is therefore not defined: use the solution of xdazz. However, you get a warning message from PHP ( Warning: POST Content-Length of xxx bytes exceeds the limit of yyy bytes in Unknown on line 0 ).
  • If the file size is between post_max_size and upload_max_filesize , in that case you can use $_FILES['fileupload']['error'] , without having to be bothered with PHP warning messages.

In short use the following code:

 if (isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > (1024*1024*(int) ini_get('post_max_size'))) < // Code to be executed if the uploaded file has size >post_max_size // Will issue a PHP warning message > if ($_FILES[$this->name]['error'] === UPLOAD_ERR_INI_SIZE) < // Code to be executed if the uploaded file has size between upload_max_filesize and post_max_size // Will not issue any PHP warning message >

Источник

cannot upload file because of size

I'm trying to upload a file using PHP! I've tried uploading PNG,JPG,PDF,TXT files, these uploads only works when the file size is around 20kb. When I try to upload files where its size is around 150KB, it prints $_FILE error = 3 and the file name lets say '1234.png' where the tmp_name is empty and the image itself as well! here's my code

ini_set('display_errors',1); error_reporting(-1); $imageTmp = addslashes($_FILES['image']['tmp_name']); //$imageTmp = $_FILES['image']['tmp_name']; $imageOldName = addslashes($_FILES['image']['name']); $imageData = file_get_contents($imageTmp); //$imageData = base64_encode($imageTmp); echo 'image temp name: '. $imageTmp .' '; echo 'error: '. $_FILES['image']['error']. ' '; echo 'image name: '. $imageOldName. ' '; echo 'image data: '. $imageData. ' '; echo 'image type:'. $_FILES['image']['type']; echo "
"; echo "POST:"; print_r($_POST); echo "FILES:"; print_r($_FILES); echo "

"; $inipath = php_ini_loaded_file(); if ($inipath) < echo 'Loaded php.ini: ' . $inipath; >else

I've tried multiple solutions such as changing the values of post_max_size = 200M and upload_max_filesize = 200M instead of 32M Here's is the result of trying to upload txt file 4KB:

image temp name: /Applications/MAMP/tmp/php/phpOc7d6a error: 0 image Name: test.txt image data: hello image type:text/plain POST:Array ( [submit] => Record Test ) FILES:Array ( [image] => Array ( [name] => test.txt [type] => text/plain [tmp_name] => /Applications/MAMP/tmp/php/phpOc7d6a [error] => 0 [size] => 405 ) ) Loaded php.ini: /Applications/MAMP/bin/php/php5.6.10/conf/php.ini 

Warning: file_get_contents(): Filename cannot be empty in path/test1.php on line 10 image temp name: error: 3 image name: IMG_8807.JPG image data: image type:

POST:Array ( ) FILES:Array ( [image] => Array ( [name] => IMG_8807.JPG [type] => [tmp_name] => [error] => 3 [size] => 0 ) ) Loaded php.ini: /Applications/MAMP/bin/php/php5.6.10/conf/php.ini 

BTW, after a failed upload, the server crashes and display 502 Gateway and I have to restart the Apache!

Источник

PHP: What's the point of UPLOAD_ERR_INI_SIZE?

The PHP manual has a section called Handling file uploads. That section has a subsection called Error Messages Explained. That subsection describes an error called "UPLOAD_ERR_INI_SIZE": Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini. However, in my experience, it's impossible to ever check for this particular error using UPLOAD_ERR_INI_SIZE because if a user ever does upload a file that exceeds the upload_max_filesize directive in php.ini, the $_FILES superglobal is empty. Want to test it for yourself? Save this as "upload_test.php" and then try to upload a file that's under the limit and then a file that's over the limit:

'; print_r($_POST); echo '

Contents of $_FILES:


'; print_r($_FILES); echo '

'; exit; > $max_filesize_in_mib = min((int)(ini_get('upload_max_filesize')), (int)(ini_get('post_max_size')), (int)(ini_get('memory_limit'))); ?>

Upload a File (Maximum File Size: MiB)

3 Answers 3

UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

This make sense when your POST_MAX_SIZE is bigger than UPLOAD_MAX_FILESIZE .

I tried in an environment where POST_MAX_SIZE is 128MB , then i set UPLOAD_MAX_FILESIZE to 1MB

Here's what i got (as expected):

Contents of $_POST: Array ( [random_field] => You should see this field in the $_POST superglobal. ) Contents of $_FILES: Array ( [upload_test] => Array ( [name] => Scan.tiff [type] => [tmp_name] => [error] => 1 [size] => 0 ) )

Although we don't get the size of the file, we do know that it's exceeding the upload_max_filesize .

Источник

Оцените статью