Get basename and file extension with PHP or Javascript

Getting file extension and basename is a common development task. PHP internal function pathinfo is very useful. But, Windows paths will not work correctly on Linux servers and vice versa. In this case you may use the alternative way (see below). In Javascript there is not a pathinfo equivalent, so you have to write custom code.

PHP

Get file extension

Using pathinfo (recommended):

$file_ext = pathinfo($filename, PATHINFO_EXTENSION);

When you have to compare file extension with a list of permitted extensions (e.g. ('png', 'jpeg', 'jpg')), get the result in lower case

$file_ext = mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION));

Alternative way

$file_ext = array_pop(explode(".", $filename));

Get basename

Using pathinfo (recommended):

$basename = pathinfo($filepath, PATHINFO_BASENAME);

Using basename:

$basename = basename($filepath);

Alternative way

$basename = preg_replace('/^.+[\\\\\\/]/', '', $filepath);

Javascript

Get file extension

var file_ext = filename.split('.').pop();

When you have to compare file extension with a list of permitted extensions (e.g. ('png', 'jpeg', 'jpg')), get the result in lower case

var file_ext = filename.split('.').pop().toLowerCase();

Get basename

var basename = filepath.replace(/\\/g,'/').replace(/.*\//, '');

CAUTION: backslash (\) is an escape character in Javascript, so you have to double backslash Windows paths such as C:\\path\\filename.ext. On the other hand, this function will work with any Linux/Unix path like /path/to/filename.ext.

References

From php documentation

Regular expressions (regex)

Your comments are welcome!


Never Miss A Post!

Subscribe to our free NewsLetter