How to Get the File Extension in PHP

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

How to get the file extension in PHP?

No need to use string functions. You can use something that's actually designed for what you want: pathinfo():

$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);

Get the file extension

Use pathinfo:

$pi = pathinfo($name);
$txt = $pi['filename'];
$ext = $pi['extension'];

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

How to get the file extension of file uploaded

Try this:

$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

Finding Extension of uploaded file (PHP)

$name = $_FILES["file"]["name"];
$ext = end((explode(".", $name))); # extra () to prevent notice

echo $ext;

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, 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


Related Topics



Leave a reply



Submit