What's the Best Way/Practice to Get the Extension of a Uploaded File in PHP

What's the best way/practice to get the extension of a uploaded file in PHP

pathinfo($_FILES['File']['name'], PATHINFO_EXTENSION)

  • Use a built-in function whenever possible (what @Sarfraz said in the meantime), and
  • Extract only the needed information (options = PATHINFO_EXTENSION)

How to get a file's extension in PHP?

People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).

In fact, it does exist, but few people know it. Meet pathinfo():

$ext = pathinfo($filename, PATHINFO_EXTENSION);

This is fast and built-in. pathinfo() can give you other information, such as canonical path, depending on the constant you pass to it.

Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:

setlocale(LC_ALL,'en_US.UTF-8');

Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.

Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.

Enjoy

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';
}

PHP check file extension

pathinfo is what you're looking for

PHP.net

$file_parts = pathinfo($filename);

switch($file_parts['extension'])
{
case "jpg":
break;

case "exe":
break;

case "": // Handle file extension for files ending in '.'
case NULL: // Handle no file extension
break;
}

What is the business best practice on validating filename?

Check filename with regexp. Use info about mimetype. Save file on server with md5 name. Store real filename on db.

PHP Upload image with md5 name

Get the file extension and add it to your $filenamekey.

$extension = pathinfo($_FILES["myfile"]["name"], PATHINFO_EXTENSION);
$filenamekey .= "." . $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 files instead of an image and execute your script for their purposes which is dangerous.

So I recommend that you not depend on the following snippet to get MIME of a file

$_FILES['input_name']['type'];

Rather I would recommend that you use this mime_content_type() function to get MIME type but with the help of other PHP's built-in functions. 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 files from now on.

PHP, get file name without file extension

No need for all that. Check out pathinfo(), it gives you all the components of your path.

Example from the manual:

$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0

Output of the code:

/www/htdocs
index.html
html
index

And alternatively you can get only certain parts like:

echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html

PHP image upload - rename without losing extension?

$ext = pathinfo($filename, PATHINFO_EXTENSION);

$newFilename = $random_digit . '.' . $ext;

BTW, what will happen if the random number clashes (which may happen next or in 10 years)?

There are many better ways to name them - for example, hash of the filename and time() should theoretically never clash (though in practice hash collisions do occur).



Related Topics



Leave a reply



Submit