PHP tutorials
It is also a good idea to limit the maximum file size which is uploaded to your server.
Identify the line which reads:
and right before it type the following:
It is important that this line is placed before the file input field otherwise it won´t work.
Now go back to the top and identify the line which reads:
Right before this line create a constant and give it a name of MAX_FILE_SIZE.
This constant will store the value which represents the file size in bytes.
Type the following:
This constant indicates that the maximum file size for upload is around 3.9KB.
Because the value is stored in the hidden field, users could easily replace it with any value and upload files of a larger size. To prevent this from happening we need to do some more validation before we allow the file to be uploaded.
Identify the line which reads:
Create a new line type in the following:
We have created a variable called $maxfs and assigned the value of the MAX_FILE_SIZE constant to it using number_format() function which will make the calculation and add KB to the end of it.
This will give us more readable result - 3.9KB rather than 4000.
This variable will be used in the message displayed if the file exceeds the maximum file size.
We have also crated a variable called $fsize and assign the initial value of false to it so that file isn´t uploaded before we perform the condition which checks if the file size doesn´t exceed the size limit.
On the next line type:
This condition checks whether the file size is larger than 0 and less or equal the value of the MAX_FILE_SIZE.
If the condition is true than the $fsize variable becomes true as well.
Now we need to add validation to our condition which executes the file upload.
Identify the following block of code:
and replace it with:
First we check if $type and $fsize are set to true and whether the text field is not empty – if everything is ok then we are checking for any errors which could occur other than size or type of the file by using switch statement and passing the error as parameter from the array created by the file field.
If the value of the error is equal 0 then the file is uploaded and the confirmation message is displayed, otherwise the error message pops in.
If the value of the error is equal 3 then another error message is displayed.
If error returns 4 then we are displaying message informing that the file has not been selected.
If text field is empty then the relevant message is displayed.
If none of the above conditions is true then the message is displayed informing that the file couldn´t be uploaded because of the wrong file format or too large file size.
You can now remove the following block of code:
and save and test your file in the browser.
The End
Website Design Company | Website Design Company Sussex | Website Design Company Chichester | Website Design Packages | Tutorials Resources | Articles | Contact
© Web Design Tutorials – Sebastian Sulinski