debian vs suse server | mysqli usage in php | current date time to know in php | auto comment fb
 


 

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)

Εγγραφή!
Sign-up for our free email newsletter. Get updates when new tutorials and tips are published. You can unsubscribe anytime with a click.

Your comments are welcomed!

This site actively encourages commenting on any post. Comments are not pre-moderated, but this community does not tolerate direct or indirect attacks, name-calling or insults. Please, read terms of use and Comment Policy at privacy policy.

More tips