How to Get a File'S 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'];

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;

How to get a file extension from path with any extension? Solved

You can get all the extensions in the directory by using the function scandir() as

$fileName = scandir("../pictures/uploads/");
$ext = "";
foreach($fileName as $files) {
if($files !== '.' && $files !== '..') {
$ext = pathinfo($files, PATHINFO_EXTENSION);
}
}
echo $ext .'<br>';

Usually scandir() returns the first two values in the array as . and .. and by if condition mentioned in the answer you can delete these unwanted values and get the answer in the pure form.

Note : scandir() returns the values in the form of array.

i got it working see below

Sample Image

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


Related Topics



Leave a reply



Submit