0

Possible Duplicate:
How to extract a file extension in PHP?

How can we get file extension with any php function?

Whether there is some built-in function in php. I am using some explode function but any other exists

Community
  • 1
  • 1

4 Answers4

4

You can use pathinfo for this:

echo pathinfo("foo.txt", PATHINFO_EXTENSION);

But rolling your own with strrpos is not difficult as well.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • I don't recall exactly what problem I had using this function, it was long time ago, something bugging about /usr/share/file/magic, but I don't remember :/ That's why I avoid using this function. Any ideas why this function might complain about not finding that path? – Saul Martínez Oct 17 '12 at 09:46
1

Yes, you can .......

Just Use the following code.......

Pass path of file to this PHP function and get extension.


    function extension($path) {
      $qpos = strpos($path, "?");

       if ($qpos!==false) $path = substr($path, 0, $qpos);

        $extension = pathinfo($path, PATHINFO_EXTENSION);

        return $extension;
       } 

Umair Aziz
  • 1,518
  • 1
  • 19
  • 29
0

Yes, using the Pathinfo() function.

<?php
    $path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
     echo $path_parts['dirname'], "\n";
     echo $path_parts['basename'], "\n";
     echo $path_parts['extension'], "\n";
     echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

The above example will output:

/www/htdocs/inc
lib.inc.php
php //your extension
lib.inc
Mob
  • 10,958
  • 6
  • 41
  • 58
0

This is the code I use to get a file extension:

$filename = '/some/path/file.txt';
$extension = strtolower(substr(strrchr($filename, '.'), 1));

You can wrap it in your Utils class or something ;)

Saul Martínez
  • 920
  • 13
  • 28
  • So why don't you use the built-in function that everyone else is referencing in their answers - do you have some secret knowledge that shows your method is better? – Mark Baker Oct 17 '12 at 09:46
  • Not at all! I used to use pathinfo(). Might be my server setup, but time ago I started to have some issues when using that function, something about not finding the path `/usr/share/file/magic` so, when I needed to export and resize some images, I took this (substr()) approach instead of pathinfo(), but c'mon, if you don't have any issues using pathinfo, go for it. ;) – Saul Martínez Oct 17 '12 at 09:53