PHP tutorials
You may also want to narrow the list of the file types which users can upload to your server through the form – let´s say you want visitors to only be able to upload .gifs, .jpgs, and .pngs and restrict all other types.
To do this we will create an array which will store the file types we want the visitors to be able to upload and anything what´s not in this array will be rejected.
Start typing after the line which reads
$file = strtolower($file); :
We have added gif, jpeg and png to our array – which means that only files with these extensions will be allowed to be uploaded.
To ensure that the Internet Explorer will accept jpeg files we had to add image/pjpeg as well – otherwise form would reject all jpeg files submitted via Internet Explorer.
Add the following on the next line:
This is assuming that the file type is incorrect by assigning value false to the new variable called $ftype and until our next piece of code will check and approve that the file type is ok, none of the files will be uploaded.
Create new line and type the following foreach loop which validates the file type:
The foreach() loop takes the values from the $filetype array which stores allowed file types and assigns them to the temporary variable called $type.
The if condition compares the uploaded file extension to the values in our array and if the match has been found the $ftype changes its status to true and the loop is terminated.
Now we need to apply the condition to our move_uploaded_file() function – so that it isn´t executed until we know that the $ftype is set to true.
Change the move_uploaded_file() function to read:
The if condition checks if the $ftype is set to true, in which case the move_uploaded_file() function is executed. If the condition is set to false then the new variable called $msg is created and the message informing about the problem is assigned to it.
Now above your form type the following – which will display the message if the file type is incorrect:
Now try to test your page in the browser. First upload the file with any of the allowed extensions and then upload the file with the different extension. If you upload the file with the file extension which isn´t listed in our array - you should get an error message above your form (Fig. 04).

Fig. 04
In the next section I´m explaining how to restrict the file size of the uploaded file.
<< Renaming file | Limiting file size >>
Website Design Company | Website Design Company Sussex | Website Design Company Chichester | Website Design Packages | Tutorials Resources | Articles | Contact
© Web Design Tutorials – Sebastian Sulinski