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.
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.
How to get the file extension of file uploaded
Try this:
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
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.
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.
Related Topics
List All Files in One Directory PHP
Trying to Get Property of Non-Object - Laravel 5
How to Show Multiple Recaptchas on a Single Page
Manipulate a String That Is 30 Million Characters Long
How to Prevent My Site Page to Be Loaded Via 3Rd Party Site Frame of Iframe
Laravel View Not Found Exception
Remove the Last Character from a String
The Character Encoding of the HTML Document Was Not Declared
Is the Leading Colon For Parameter Names Passed to Pdostatement::Bindparam() Optional
How to Implement a Web Scraper in PHP
Converting a Number With Comma as Decimal Point to Float
Creating PHP Class Instance With a String
PHP Json_Encode Class Private Members
Instantiate a Class from a Variable in PHP
PHP Threading Call to a PHP Function Asynchronously
What Is Autoloading; How to Use Spl_Autoload, _Autoload and Spl_Autoload_Register