How to limit file size during file uploading using PHP?
By admin at 24 July, 2008, 2:39 pm
I expect that the previous post regarding to the file upload becomes beneficial to you. Now let us become more specific. You may like to restrict user in many circumstances. So, today I am going to deal with the restriction made to the file size during the file uploads. There may be many solutions. Let me share - some of them.
Method 1.
You can place hidden field as
1 2 | <input type="hidden" name="MAX_FILE_SIZE" value="2000000" /> |
Note :: Well, some web browsers actually pick up on this field and will not allow the user to upload a file bigger than this number (in bytes). You should set this value to coincide with the maximum upload size that is set in your php.ini file. It is set with the upload_max_filesize directive and the default is 2MB. But it still cannot ensure that your script won’t be handed a file of a larger size. The danger is that an attacker will try to send you several large files in one request and fill up the file system in which PHP stores the decoded files. Set the post_max_size directive in your php.ini file to the maximum size that you want (must be greater than upload_max_filesize). The default is 10MB. This directive controls the maximum size of all the POST data allowed in a single request. Also make sure that file_uploads inside your php.ini file is set to On.
Method 2.
On the other hand, You may define and validate the file size before uploading , as—
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php //check for valid file size in bytes function validate_file_size($file_name, $max_file_size) { $size = filesize($file_name); if ($size > $max_file_size) { return FALSE; }else{ return TRUE; } }//end of function validate_file_size ?> |
Method 3.
There is another way which is quite simple one.The superglobal $_FILES array containing information about the file; namely $_FILES["userfile"]["size"] gives you the size of the uploaded file in bytes. So by cheking the size you may restrict user during file uploading.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php define("MAX_SIZE",2000000); if($_FILES["userfile"]["size"] < MAX_SIZE){ if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) { echo "The file has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } }else{ echo "There was an error uploading the file, please try again!"; } ?> |
Spread the Words!
Sorry, the comment form is closed at this time.
No comments yet.