Check file extension in upload form in PHP
Using if( $ext !== 'gif'
) might not be efficient. What if you allow like 20 different extensions?
Try:
$allowed = array('gif', 'png', 'jpg');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
echo 'error';
}
How to check uploaded file type in PHP
Never use $_FILES..['type']
. The information contained in it is not verified at all, it's a user-defined value. Test the type yourself. For images, exif_imagetype
is usually a good choice:
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
Alternatively, the finfo
functions are great, if your server supports them.
How to check file types of uploaded files in PHP?
Take a look at mime_content_type or Fileinfo. These are built-in PHP commands for determining the type of a file by looking at the contents of the file. Also check the comments on the above two pages, there are some other good suggestions.
Personally I've had good luck using something that's essentially system("file -bi $uploadedfile")
, but I'm not sure if that's the best method.
PHP: How to properly check MIME type of a file?
To get MIME type, developers generally depend on $_FILES['input_name']['type']
. But this is absolutely vulnerable. Because a malicious user can set one of image/jpg
, image/png
, image/gif
etc. MIME types to a file that is not actually an image. In that case, the malicious user may get your script pass to upload other file instead of an image and execute your script for their purposes which is dangerous.
So I recommend that you do not depend on the following snippet to get MIME of a file
$_FILE['input_name']['type'];
Rather I would recommend use this mime_content_type()
function to get MIME type but with the help of other PHP's built-in function. And that is is_uploaded_file()
function. What it does is:
This is useful to help ensure that a malicious user hasn't tried to
trick the script into working on files upon which it should not be
working--for instance, /etc/passwd.This sort of check is especially important if there is any chance that
anything done with uploaded files could reveal their contents to the
user, or even to other users on the same system.
So to make this function work properly it needs a specific argument. Check out the code below:
if (is_uploaded_file($_FILES['input_name']['tmp_name'])) {
// Do other stuff.
}
This function returns true
on success, false
otherwise. So if it returns true
then you're ok with the file. Thanks to this function. Now mime_content_type()
function comes into play. How? Look at the code below:
if (is_uploaded_file($_FILES['input_name']['tmp_name'])) {
// Notice how to grab MIME type.
$mime_type = mime_content_type($_FILES['input_name']['tmp_name']);
// If you want to allow certain files
$allowed_file_types = ['image/png', 'image/jpeg', 'application/pdf'];
if (! in_array($mime_type, $allowed_file_types)) {
// File type is NOT allowed.
}
// Set up destination of the file
$destination = '/path/to/move/your/file/';
// Now you move/upload your file
if (move_uploaded_file ($_FILES['input_name']['tmp_name'] , $destination)) {
// File moved to the destination
}
}
BTW, for novice, do not try remote url with this function to get MIME type. The code below will not work:
mime_content_type('http://www.example.com/uploads/example.png');
But the one below would work:
mime_content_type('/source/to/your/file/etc.png');
Hope you would enjoy uploading file from now on.
How to get the file extension of file uploaded
Try this:
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
PHP Upload with file type and size check
This answer provides the solution to check size before uploading to data to the server. This makes sense. If you do a client check, you can eliminate unnecessary posts to your server. A sanity check on the server remains necessary, JavaScript code on the client can be altered. The other answers provide explanation on how to improve your server side code.
var mimeTypes = [
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", //docx
"application/pdf", //pdf
"application/msword", //doc
"rtf;application/rtf", //rtf
"rtf;application/x-rtf",
"rtf;text/richtext",
"application/vnd.oasis.opendocument.text" //odt
]
function readFiles(files)
{
var iMax = files.length;
var sum = "";
var max = 2097152;
for (var i = 0; i < iMax; i++)
{
var fileType = files[i].type;
var fileSize = files[i].size;
sum += parseInt(fileSize);
if (mimeTypes.indexOf(files[i].type) == -1)
{
alert("Invalid file selected");
return false;
}
}
if (sum > max)
{
alert("Total file size exceeds maximum upload size.");
return false;
}
return true;
}
document.getElementById("form").querySelector("input[type='file']").addEventListener("change", readFiles, false);
readFiles
fires whenever a change event is fired on the file input. In browsers supporting HTML5 input elements you can read out the file type
and file size
property. They are inherited from the Blob
object. You can even pass the file to a FileReader object allowing you to read the contents of the file.
Bug in IE 10, 11. On IE10 and 11 there is a bug present that returns an empty string on
file-type
when used on images. You can work around this by checking the extension.
How can I check uploaded files extension?
If you run on your server(s) linux I would check the file content type with the command file
that returns the real mime type of the file. Than you can be sure what that content is (in most cases).
That programm uses that magic bytes. The orginal idea is to check the first view bytes and check if a file contains a known pattern, e.g. "MZ" for windows executables or "‰PNG" for png files. However that file
programm does also some more things than only the basic set of the first view bytes.
Depending on the comments, you are concerned about wrong, e.g. double file extensions. I would say don't think about it and just rename that file, in best case with some random name. That could be also helpful if you worry about that somebody just counts up some file numbers to see unpublished images.
Related Topics
How to Recursively Delete a Directory and Its Entire Contents (Files + Sub Dirs) in PHP
Post Request in Laravel - Error - 419 Sorry, Your Session/ 419 Your Page Has Expired
PHP Warning: PHP Startup: How to Load Dynamic Library
How Create an Array from the Output of an Array Printed With Print_R
How to Upload Images into MySQL Database Using PHP Code
How to Bind MySQLi Bind_Param Arguments Dynamically in PHP
Max Size of Url Parameters in _Get
Redraw Google Chart Based on User Input Via Ajax Request
Example of How to Use Bind_Result VS Get_Result
How to Make a PHP Soap Call Using the Soapclient Class
Run Process With Realtime Output in PHP
Download File Through an Ajax Call PHP
Search With Comma-Separated Value MySQL
PHP Regex to Get Youtube Video Id
What Are the Disadvantages of Using Persistent Connection in Pdo