Recently, I found an issue with checking a file’s type while using the simple upload form. After some investigation I found why the code for checking a file’s extension type wasn’t working as well as an alternative to solve the problem.
Here’s the code for the form I used:
<form action="test.php" enctype="multipart/form-data" method="POST">
Choose a file to upload: <input type="file" name="uploadedfile" />
<input type="submit" value="Upload File" /></form>
For simplicity, I got this sample of PHP code from here.
Now, usually I would use the $_FILES array to test a file’s type during processing to decide whether to accept or reject the file but the $_FILES[“filename”][“type”] result (even though correct) would not respond to my request as planned.
The hint (in regards to $_FILES[“filename”][“type”]) I found was on php.net website which states the following: “The mime type of the file, if the browser provided this information. An example would be “image/gif”. This mime type is however not checked on the PHP side and therefore don’t take its value for granted.”
So, an alternative solution to this is to retrieve the file’s full name including extension using $_FILES[“filename”][“name”], explode the name using a period ( . ), and lastly use the last piece of array (which is the resulting extension) to match it with what you want. Here’s a sample of the working code:
// save the file name in a variable
$filename = trim($_FILES["uploadedfile"]["name"]);
// explode the file name
$pieces = explode('.', $filename);
// if file extension is not jpg then display an error message
if(trim($pieces) != "jpg")
echo "This file format is not accepted.";
echo "Congratulations, the file is valid.";
I hope this helps. Enjoy it.