854

This is a question you can read everywhere on the web with various answers:

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

$exts = split("[/\\.]", $filename);
$n    = count($exts)-1;
$ext  = $exts[$n];

etc.

However, there is always "the best way" and it should be on Stack Overflow.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Bite code
  • 578,959
  • 113
  • 301
  • 329

31 Answers31

1962

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

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28
Bite code
  • 578,959
  • 113
  • 301
  • 329
  • my pathinfo is disabled then short way to extract extension string ? – khizar ansari Aug 10 '12 at 18:20
  • 24
    @khizaransari You should look for another hosting provider, the one you got is stupid. Really, I mean it. There is _no reason whatsoever_ to disable this function. Tell them that. As a workaround: `function get_ext($fname){ return substr($fname, strrpos($fname, ".") + 1); }` Make sure the file has an extension though, it may do anything when you pass a path as argument! – Luc Sep 20 '12 at 17:29
  • I have a problem with this example - it doesn't work for names like ".............doc", any ideas why ? – Bor Dec 19 '13 at 08:33
  • 13
    my idea of PHP compared to python changed completely now that I know about this function :O – Tommaso Barbugli Jul 02 '14 at 10:22
  • @e-satis but its not working in one scenario in my application, Like some times I am getting a URL in following format , `www.domain.com/image.php?id=123&idlocation=987&number=01` to download the images since this uRL does not have the image name or extention the pathifo() is failling to give us the image extension . SO what should be done please!!! help me – Vikram Anand Bhushan Apr 06 '15 at 12:37
  • It's really not fair that I did not waste as much as some of the other people here, and instead found this answer and solved my problem quickly. – ted.strauss Apr 14 '15 at 20:07
  • 4
    This is NOT a secure solution. If someone uploaded to your endpoint without using a browser they could spoof the extension. For example: pathinfo('image.jpg.spoofed',PATHINFO_EXTENSION) returns 'spoofed' !! It does not check actual file body since it doesn't take the file path, and it does not verify its result with a MimeType Map. You should ensure the value you receive from this is in fact a valid type by querying http://www.iana.org/assignments/media-types/media-types.txt or by checking your own MimeType Map. – John Foley Apr 23 '15 at 01:11
  • **BE CAREFULL!!!!! THIS IS NOT SAFE FUNCTION !!!** read other answers! – T.Todua Nov 21 '16 at 11:31
  • **This is a very slow way** to do it, pathinfo does a lot more than what you're looking for and it's all discarded on return. I added another answer with some time measurements. – dkellner Apr 07 '20 at 11:38
193

pathinfo()

$path_info = pathinfo('/foo/bar/baz.bill');

echo $path_info['extension']; // "bill"
T.Todua
  • 53,146
  • 19
  • 236
  • 237
Adam Wright
  • 48,938
  • 12
  • 131
  • 152
  • 15
    Since PHP 5.5 -> `echo pathinfo('/foo/bar/baz.bill')['extension'];` – Salman A Sep 13 '14 at 12:18
  • 1
    This even works on this level (Twitter json): $ext = pathinfo($result->extended_entities->media[0]->video_info->variants[1]->url, PATHINFO_EXTENSION); – KJS Dec 04 '16 at 01:01
125

Example URL: http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ

A) Don't use suggested unsafe PATHINFO:

pathinfo($url)['dirname']    'http://example.com/myfolder'
pathinfo($url)['basename']   'sympony.mp3?a=1&b=2#XYZ'         // <------- BAD !!
pathinfo($url)['extension']  'mp3?a=1&b=2#XYZ'                 // <------- BAD !!
pathinfo($url)['filename']   'sympony'

B) Use PARSE_URL:

parse_url($url)['scheme']    'http'
parse_url($url)['host']      'example.com'
parse_url($url)['path']      '/myfolder/sympony.mp3'
parse_url($url)['query']     'aa=1&bb=2'
parse_url($url)['fragment']  'XYZ'

BONUS: View all native PHP examples

dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 5
    This answer covers everything eg. a file like `foo_folder/foo-file.jpg?1345838509` will fail miserably with just `pathinfo`, thanx –  Jul 20 '15 at 06:46
  • 2
    Not completely on-topic, but it sure did solve my problem! – Howie Nov 24 '15 at 06:48
  • 16
    Don't forget nothing! `parse_url` is for URL and `pathinfo` is for file path. – Nabi K.A.Z. Jun 09 '17 at 06:02
  • 1
    What do you mean "forget path info"? You use it in the solution! – Autumn Leonard Jun 20 '17 at 14:12
  • 2
    @AutumnLeonard He doesn't, he just showed the differences between pathinfo and parse_url. –  Aug 29 '17 at 09:52
  • for those who have problem with file names like Webp.net-resizeimage_%288%29.png?1547034073 where we have multiple dots you can use php end() function to get last item of array than includes the file format – Artin GH Jul 01 '20 at 11:13
  • Naturally, you shouldn't use pathinfo with a url. – Herbert Van-Vliet May 06 '21 at 08:02
  • `pathinfo()` would be the best solution if used on `$_FILES` (POST upload). So it works well, as long that it is used correctly. If the original question was about how to get an extension out from an URL with query string parameters, then yes, in that case your solution would have been correct. – funder7 Jun 02 '22 at 10:10
  • 2
    Parse URL doesn't get the file extension which is what the question asks. The filename is already acquired in the question so while a good comparison is not a good answer. – Brad Aug 31 '22 at 01:37
  • It all depends on what you know about the input. If you KNOW it's a local path with a filename, parse_url() is pointless. If it's an URL, sure, get the path fragment first. Also, if it's a whole book about an URL, strip the rest of the book first, then parse the URL. You see where I'm going. pathinfo is not unsafe, unless you misuse it by giving it something unexpected, like a whole URL. – dkellner Nov 17 '22 at 08:25
  • Good point, but the question was for the file's extension. This answer + that answer https://stackoverflow.com/a/61079134/2444812 seems like a good solution. – Sybille Peters Apr 25 '23 at 13:17
71

There is also SplFileInfo:

$file = new SplFileInfo($path);
$ext  = $file->getExtension();

Often you can write better code if you pass such an object around instead of a string. Your code is more speaking then. Since PHP 5.4 this is a one-liner:

$ext  = (new SplFileInfo($path))->getExtension();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Fantastic, Its Objects all the way down :) – Christopher Chase Jun 26 '13 at 15:12
  • 3
    Please be aware that `->getExtension()` is available in SplFileInfo since PHP 5.3.6. – matthias Aug 26 '14 at 12:02
  • 1
    @matthias: Please be aware that SPL can be disabled in PHP versions that predate the PHP 5.3.0 release. If you're still not running PHP 5.3 but 5.2 or lower, this answer most likely did not fit for stable code. Otherwise you can stabilize your code by requiring a specific PHP version and otherwise bail out. – hakre Aug 26 '14 at 12:24
  • @hakre While you're correct in saying it "can be disabled in versions predating 5.3.0", the SPL extension is nevertheless compiled in by default as of PHP 5.0.0. So this comment makes indeed sense for people forced to use PHP 5.2 or lower and don't want to resign using specific SPL classes. – matthias Aug 26 '14 at 12:35
  • `$ext = pathinfo($file, PATHINFO_EXTENSION)` or `$ext = pathinfo($file)['extension']` are better one-liners. – Iiridayn Mar 16 '18 at 18:50
  • This answer is useful when you want an extension from a simple string – Alcalyn Mar 16 '21 at 09:26
50

Do it faster!

In other words, if you only work with a filename, please stop using pathinfo.

I mean, sure if you have a full pathname, pathinfo makes sense because it's smarter than just finding dots: the path can contain dots and filename itself may have none. So in this case, considering an input string like d:/some.thing/myfile, pathinfo and other fully equipped methods are a good choice.

But if all you have is a filename, with no path, it's simply pointless to make the system work a lot more than it needs to. And this can give you a 10x speed boost.

Here's a quick speed test:

/*   387 ns */ function method1($s) {return preg_replace("/.*\./","",$s);} // edge case problem
/*   769 ns */ function method2($s) {preg_match("/\.([^\.]+)$/",$s,$a);return $a[1];}
/*    67 ns */ function method3($s) {$n = strrpos($s,"."); if($n===false) return "";return substr($s,$n+1);}
/*   175 ns */ function method4($s) {$a = explode(".",$s);$n = count($a); if($n==1) return "";return $a[$n-1];}
/*   731 ns */ function method5($s) {return pathinfo($s, PATHINFO_EXTENSION);}
/*   732 ns */ function method6($s) {return (new SplFileInfo($s))->getExtension();}

//  All measured on Linux; it will be vastly different on Windows

Those nanosecond values will obviously differ on each system, but they give a clear picture about proportions. SplFileInfo and pathinfo are great fellas, but for this kind of job it's simply not worth it to wake them up. For the same reason, explode() is considerably faster than regex. Very simple tools tend to beat more sophisticated ones.

Conclusion

This seems to be the Way of the Samurai:

function fileExtension($name) {
    $n = strrpos($name, '.');
    return ($n === false) ? '' : substr($name, $n+1);
}

Remember this is for simple filenames only. If you have paths involved, stick to pathinfo or deal with the dirname separately.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
dkellner
  • 8,726
  • 2
  • 49
  • 47
  • 3
    Thanks a ton for this. It's always nice to find those well-researched newer answers on older questions. Saves time figuring out what techniques might be outdated. – Leon Williams Jan 23 '21 at 06:31
  • strrpos method might need another check for this case with no extension "filename." – ungalcrys Feb 02 '21 at 12:48
  • 1
    @ungalcrys in that case, substr will take an empty portion so the extension itself will be "", just as it should. – dkellner Feb 02 '21 at 13:30
  • @dkellner care to also benchmark `$info = new SplFileInfo('test.png');$info->getExtension();`? – Timo Huovinen May 11 '21 at 12:48
  • 1
    @TimoHuovinen The server I used for this benchmark now gets totally different results. Probably there was a php update too, but for sure it's a stronger hardware. Anyway, while phpinfo is now approximately the same as method1, splFileInfo is just as slow, even a little bit slower. I think I'm gonna update the charts. – dkellner May 11 '21 at 14:04
  • This seems to be an optimization that fits better in the C implementation of pathinfo or some other standard library function? In general I'd like to make the remark that if you have no performance scaling issues, have not done any profiling and have not reached the conclusion that this is an important culprit it's probably premature optimization to write this function yourself. Also, what happens if `there.are.multiple.dots.in.your.filename`? – Tim Strijdhorst Aug 25 '22 at 11:10
  • @TimStrijdhorst - it should work as expected with several dots. Also, it's very important to write code with speed in mind. – dkellner Aug 25 '22 at 11:39
  • Nice answer. For completeness, I'd show the speed of `basename()` to see if it could still be faster to avoid path info or spl if you have to start with a full path. Perhaps also include `realpath` as it might indicate pathinfo or spl worthy if you suddenly need 3 operations if you get me. Also like to point out that all your benchmarks are wrapped in a function when some do not need the function overhead but others such as the `strrpos` method require function wrappers and that in itself slows it down. Pathinfo may be faster because it needs no function wrapper to be easily repeated. – Brad Aug 31 '22 at 02:05
  • @Brad: extra tests are always welcome. But for filenames with no path, there's no need to use basename, and realpath only works for existing files (which is not necessarily the case - it could be a moment before you even create the file), so these are different concerns. Yes I see your point btw, but that's why I made it clear that this is only about filenames. – dkellner Aug 31 '22 at 23:21
  • I also appreciate well researched responses, and there are times when speed is really important. But... the 10x speed boost you're talking about here (which is probably less now) is roughly {a millionth of a second} vs {a ten-millionth of a second}. If a script processes 1,000 filenames, the savings of using your fastest solution would amount to less than 1 millisecond. I ended up on this page because I'm writing a script that will process 30-40 files in a cron job. The time savings would be literally worthless. Readability and reliability are often more important than speed. – davidreedernst Nov 16 '22 at 14:01
  • 1
    @davidreedernst - "fileExtension" is quite readable. Also, for 50-100 iterations you don't need super speed. Imagine a logfile with 15M items. – dkellner Nov 17 '22 at 08:20
26

As long as it does not contain a path you can also use:

array_pop(explode('.', $fname))

Where $fname is a name of the file, for example: my_picture.jpg. And the outcome would be: jpg

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anonymous
  • 4,692
  • 8
  • 61
  • 91
24

E-satis's response is the correct way to determine the file extension.

Alternatively, instead of relying on a files extension, you could use the fileinfo to determine the files MIME type.

Here's a simplified example of processing an image uploaded by a user:

// Code assumes necessary extensions are installed and a successful file upload has already occurred

// Create a FileInfo object
$finfo = new FileInfo(null, '/path/to/magic/file');

// Determine the MIME type of the uploaded file
switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME)) {        
    case 'image/jpg':
        $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
    break;

    case 'image/png':
        $im = imagecreatefrompng($_FILES['image']['tmp_name']);
    break;

    case 'image/gif':
        $im = imagecreatefromgif($_FILES['image']['tmp_name']);
    break;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Toxygene
  • 487
  • 3
  • 10
  • 1
    This is the ONLY correct answer. I don't understand why people voted-up others. Yes, this approach demands more efforts from developer but it boosts performance(although little, but it does). Please refer [this](http://www.php.net/manual/en/function.pathinfo.php#47867). – Bhavik Shah Jan 31 '14 at 07:43
  • 7
    @Bhavik : In some cases we may only need the file extension, they about the mime type check. But the actual question is about file extension, not file type. So this is NOT the best answer for this question. (yet an answer) – Sasi varna kumar Oct 23 '15 at 08:25
  • A filename doesn't even mean that the file exists, so anything relying on the contents is wrong in the first place. Then, even if there's an actual file, it's a lot slower to open it than to just know the name, and also you can't even be sure you have the rights to access the file itself. Not to mention locking and other potential problems. So no. It's not the best answer, far from it actually. – dkellner Jun 09 '22 at 10:40
14

1) If you are using (PHP 5 >= 5.3.6) you can use SplFileInfo::getExtension — Gets the file extension

Example code

<?php

$info = new SplFileInfo('test.png');
var_dump($info->getExtension());

$info = new SplFileInfo('test.tar.gz');
var_dump($info->getExtension());

?>

This will output

string(3) "png"
string(2) "gz"

2) Another way of getting the extension if you are using (PHP 4 >= 4.0.3, PHP 5) is pathinfo

Example code

<?php

$ext = pathinfo('test.png', PATHINFO_EXTENSION);
var_dump($ext);

$ext = pathinfo('test.tar.gz', PATHINFO_EXTENSION);
var_dump($ext);

?>

This will output

string(3) "png"
string(2) "gz"

// EDIT: removed a bracket

nils
  • 1,668
  • 14
  • 15
Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102
12

Sometimes it's useful to not to use pathinfo($path, PATHINFO_EXTENSION). For example:

$path = '/path/to/file.tar.gz';

echo ltrim(strstr($path, '.'), '.'); // tar.gz
echo pathinfo($path, PATHINFO_EXTENSION); // gz

Also note that pathinfo fails to handle some non-ASCII characters (usually it just suppresses them from the output). In extensions that usually isn't a problem, but it doesn't hurt to be aware of that caveat.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • 6
    @e-satis: According to [Wikipedia](http://en.wikipedia.org/wiki/Filename_extension) they are two extensions: *The UNIX-like filesystems use a different model without the segregated extension metadata. The dot character is just another character in the main filename, and filenames can have multiple extensions, usually representing nested transformations, such as files.tar.gz*. – Alix Axel Nov 01 '12 at 23:29
  • 1
    And if we have dot in the product name? Ex : `test.19-02-2014.jpeg` – Mario Radomanana Mar 26 '14 at 14:05
  • 1
    This will fail with /root/my.folder/my.css `ltrim(strrchr($PATH, '.'),'.')` works like pathinfo, but without tokenizing everything. – Ray Foss Sep 09 '16 at 13:46
11

Sorry... "Short Question; But NOT Short Answer"

Example 1 for PATH

$path = "/home/ali/public_html/wp-content/themes/chicken/css/base.min.css";
$name = pathinfo($path, PATHINFO_FILENAME);
$ext  = pathinfo($path, PATHINFO_EXTENSION);
printf('<hr> Name: %s <br> Extension: %s', $name, $ext);

Example 2 for URL

$url = "//www.example.com/dir/file.bak.php?Something+is+wrong=hello";
$url = parse_url($url);
$name = pathinfo($url['path'], PATHINFO_FILENAME);
$ext  = pathinfo($url['path'], PATHINFO_EXTENSION);
printf('<hr> Name: %s <br> Extension: %s', $name, $ext);

Output of example 1:

Name: base.min
Extension: css

Output of example 2:

Name: file.bak
Extension: php

References

  1. https://www.php.net/manual/en/function.pathinfo.php

  2. https://www.php.net/manual/en/function.realpath.php

  3. https://www.php.net/manual/en/function.parse-url.php

Ali Han
  • 509
  • 7
  • 10
10

The simplest way to get file extension in PHP is to use PHP's built-in function pathinfo.

$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // The output should be the extension of the file e.g., png, gif, or html
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shahbaz
  • 3,433
  • 1
  • 26
  • 43
9

You can try also this (it works on PHP 5.* and 7):

$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip

Tip: it returns an empty string if the file doesn't have an extension

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pooya_sabramooz
  • 168
  • 1
  • 5
7

The "best" way depends on the context and what you are doing with that file extension. However,

pathinfo in general is the best when you consider all the angles.

pathinfo($file, PATHINFO_EXTENSION)

It is not the fastest, but it is fast enough. It is easy to read, easy to remember and reuse everywhere. Anyone can understand it at a glance and remove PATHINFO_EXT flag if they need more info about the file.

strrpos method. described in several answers is faster yes but requires additional safety checks which, in turn, requires you to wrap it inside a function, to make it easily reusable. Then you must take the function with you from project to project or look it up. Wrapping it in a function call with extra checks also makes it slower and if you need any other info about the file you now have other methods to call and at that point, you lose the speed advantage anyway whilst having a solution that's harder to read. The potential for speed is there but is not worth it unless you need to address such a bottleneck.

❌ I'd also rule out any ideas using substr, explode, and most other manual manipulations for the same reasons mentioned above.

SplFileInfo is very cool but takes up much more brain space with a lot of interfaces that you no doubt waste time learning only to look them up again next time. I'd only use it in specific cases where you will find the extra interfaces worth someone learning Spl when they come back to add/edit your code later.

❌ I would not consider preg_replace at all as any regex function in PHP is on average 3 times slower than any other function, is harder to read, and is in most cases can easily be done with something simpler. Regex is powerful and it has its place in those specific situations where it can replace several method calls and condition checks in one line. Getting a file extension this way is like using an anvil to hammer in a nail.


While of course "the best" would come down to public opinion, I'd argue that other methods are only "the best" in specialized cases.

For example, if you just want to check for a specific type then I wouldn't use any of the suggested methods as stripos would be the fastest case insensitive comparison to use.

if (stripos('/here/is/sOme.fiLe.PdF', '.pdf', -4) !== false )
{
    //its a pdf file
}

But again pathinfo would still be nicer to read and probably worth the performance cost.

But what about https://ome.Com.///lica.ted?URLS ?

Extracting paths from URLs is a separate concern that is outside the scope of the question and will require an extra step in any case where a simple one-time string comparison won't do.

Brad
  • 741
  • 7
  • 17
6
substr($path, strrpos($path, '.') + 1);
Kurt Zhong
  • 7,308
  • 1
  • 19
  • 15
  • 1
    This will fail with /root/my.folder/my.css – Ray Foss Sep 09 '16 at 13:44
  • 1
    This must work correctly: substr($path, strrpos($path,'.')+1); Note: this method is faster than any other solutions above. Try a benchmark using our own script. – Abbas Oct 17 '16 at 05:04
  • It's very fast but has a serious problem with files having no extension at all. It would strip the first character in such cases. See my solution above (Ctrl+F and type samurai); almost the same, with this tiny difference. So yes, the method is indeed cool and super fast but you should watch out for edge cases. – dkellner Apr 27 '21 at 21:57
6

Here is an example. Suppose $filename is "example.txt",

$ext = substr($filename, strrpos($filename, '.', -1), strlen($filename));

So $ext will be ".txt".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
G. I. Joe
  • 1,585
  • 17
  • 21
6

pathinfo is an array. We can check directory name, file name, extension, etc.:

$path_parts = pathinfo('test.png');

echo $path_parts['extension'], "\n";
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['filename'], "\n";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arshid KV
  • 9,631
  • 3
  • 35
  • 36
5

A quick fix would be something like this.

// Exploding the file based on the . operator
$file_ext = explode('.', $filename);

// Count taken (if more than one . exist; files like abc.fff.2013.pdf
$file_ext_count = count($file_ext);

// Minus 1 to make the offset correct
$cnt = $file_ext_count - 1;

// The variable will have a value pdf as per the sample file name mentioned above.
$file_extension = $file_ext[$cnt];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
version 2
  • 1,049
  • 3
  • 15
  • 36
  • Why not just to use php built in function for the purpose http://php.net/manual/en/function.pathinfo.php instead of using long code – Shahbaz Jul 01 '15 at 05:40
  • 1
    Besides Shahbaz's point you can also just do `$file_ext = end(explode('.', $filename));` to do everything in this answer in a single line instead of four. – tvanc Jan 07 '16 at 02:49
  • @Amelia What if you have `.tar.gz`. It will not work, so if you need to get full of extension use such as `ltrim(strstr($filename, '.'), '.');` to get full of extension instead uncorrectly as `gz`. – Marin Sagovac May 21 '16 at 20:00
5

IMO, this is the best way if you have filenames like name.name.name.ext (ugly, but it sometimes happens):

$ext     = explode('.', $filename); // Explode the string
$my_ext  = end($ext); // Get the last entry of the array

echo $my_ext;
Tommy89
  • 121
  • 1
  • 5
4

I found that the pathinfo() and SplFileInfo solutions works well for standard files on the local file system, but you can run into difficulties if you're working with remote files as URLs for valid images may have a # (fragment identifiers) and/or ? (query parameters) at the end of the URL, which both those solutions will (incorrect) treat as part of the file extension.

I found this was a reliable way to use pathinfo() on a URL after first parsing it to strip out the unnecessary clutter after the file extension:

$url_components = parse_url($url); // First parse the URL
$url_path = $url_components['path']; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()
Jonathan Ellis
  • 5,221
  • 2
  • 36
  • 53
4

You can try also this:

 pathinfo(basename($_FILES["fileToUpload"]["name"]), PATHINFO_EXTENSION)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
smile 22121
  • 285
  • 4
  • 20
4

In one line:

pathinfo(parse_url($url,PHP_URL_PATH),PATHINFO_EXTENSION);
RafaSashi
  • 16,483
  • 8
  • 84
  • 94
3

Use substr($path, strrpos($path,'.')+1);. It is the fastest method of all compares.

@Kurt Zhong already answered.

Let's check the comparative result here: https://eval.in/661574

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abbas
  • 552
  • 5
  • 8
  • Nope. It is not the fastest AND it will give you a little surprise if you call it with a filename that has no extension. – dkellner Aug 06 '20 at 23:42
2

This will work

$ext = pathinfo($filename, PATHINFO_EXTENSION);
Deepika Patel
  • 2,581
  • 2
  • 19
  • 13
  • This has already been answered much better by Subodh back in August. – Nisse Engström Jan 15 '15 at 12:18
  • 3
    This was already suggested back in 2008. Please only post an answer if you have something unique and valuable to give. Redundant content only wastes the time of researchers and bloats Stack Overflow pages. – mickmackusa Jun 28 '20 at 04:03
2

You can get all file extensions in a particular folder and do operations with a specific file extension:

<?php
    $files = glob("abc/*.*"); // abc is the folder all files inside folder
    //print_r($files);
    //echo count($files);
    for($i=0; $i<count($files); $i++):
         $extension = pathinfo($files[$i], PATHINFO_EXTENSION);
         $ext[] = $extension;
         // Do operation for particular extension type
         if($extension=='html'){
             // Do operation
         }
    endfor;
    print_r($ext);
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2
ltrim(strstr($file_url, '.'), '.')

this is the best way if you have filenames like name.name.name.ext (ugly, but it sometimes happens

Salman Zafar
  • 3,844
  • 5
  • 20
  • 43
Anjani Barnwal
  • 1,362
  • 1
  • 17
  • 23
  • To me this doesn't make sense. It only removes everything that comes before the first . (dot) and returns everything afterwards. Which means that if you have something like: **www.indexpage.com/videos/phpExtensions.mp4?v/345** your proposed method will return **indexpage.com/videos/phpExtensions.mp4?v/345** and that's not a file extension. Or did I miss something? – Relcode Mar 14 '22 at 07:06
  • yeah, this doesn't work how he suggests at all. – Brad Aug 31 '22 at 01:45
2

$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $fileName);

preg_replace approach we using regular expression search and replace. In preg_replace function first parameter is pattern to the search, second parameter $1 is a reference to whatever is matched by the first (.*) and third parameter is file name.

Another way, we can also use strrpos to find the position of the last occurrence of a ‘.’ in a file name and increment that position by 1 so that it will explode string from (.)

$ext = substr($fileName, strrpos($fileName, '.') + 1);

1

If you are looking for speed (such as in a router), you probably don't want to tokenize everything. Many other answers will fail with /root/my.folder/my.css

ltrim(strrchr($PATH, '.'),'.');
Ray Foss
  • 3,649
  • 3
  • 30
  • 31
1

Although the "best way" is debatable, I believe this is the best way for a few reasons:

function getExt($path)
{
    $basename = basename($path);
    return substr($basename, strlen(explode('.', $basename)[0]) + 1);
}
  1. It works with multiple parts to an extension, eg tar.gz
  2. Short and efficient code
  3. It works with both a filename and a complete path
Dan Bray
  • 7,242
  • 3
  • 52
  • 70
0

Actually, I was looking for that.

<?php

$url = 'http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ';
$tmp = @parse_url($url)['path'];
$ext = pathinfo($tmp, PATHINFO_EXTENSION);

var_dump($ext);
Fred
  • 868
  • 10
  • 22
0

I tried one simple solution it might help to someone else to get just filename from the URL which having get parameters

<?php

$path = "URL will be here";
echo basename(parse_url($path)['path']);

?>

Thanks

Ashok Chandrapal
  • 1,020
  • 7
  • 27
-1

Use

str_replace('.', '', strrchr($file_name, '.'))

for a quick extension retrieval (if you know for sure your file name has one).

AlexB
  • 133
  • 1
  • 1