Determine a File Extension Using PHP

There are several ways determine a file extension using PHP. First is using the combination of strrpos() and substr() function like this :

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

For example, if $fileName is my-new-house.jpg then strrpos($fileName, ‘.’) will return the last location a dot character in $fileName which is 15. So substr($fileName, strrpos($fileName, ‘.’) + 1) equals to substr($fileName, 16) which return ‘jpg’

The second is using strrchr() and substr() :

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

/*
strrchr($fileName) returns '.jpg' so substr(strrchr($fileName, '.'), 1) equals to substr('.jpg', 1) which returns 'jpg'
*/
  • jbrass // 3rd February, 2012 at 02:16 AM

    you can also use pathinfo with the PATHINFO_EXTENSION arg

    $extension = pathinfo($path, PATHINFO_EXTENSION);
    

POST A COMMENT

  • You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>