Coding Triumph

Helpful code snippets & tutorials

How to get a file extension with PHP

In this post, I’ll show you how to extract a file extension with PHP using the fast and built-in function phpinfo().

1. Get the extension of a file path

$path = '/path/to/the/file/my_file.txt';

# get file extension
$extension  = pathinfo($path, PATHINFO_EXTENSION);
echo $extension . "\n"; # "txt

# you can also get the file name
$name = pathinfo($path, PATHINFO_FILENAME);
echo $name . "\n"; # "my_file

2. Get the extension of a URL file

$url = ';

# parse the URL
$parsed_url = parse_url($url);

# get file extension
$extension  = pathinfo($parsed_url['path'], PATHINFO_EXTENSION);
echo $extension . "\n"; # "txt

# or you can get the file name
$name = pathinfo($parsed_url['path'], PATHINFO_FILENAME);
echo $name . "\n"; # "my_file

Note: phpinfo() doesn’t take into consideration the file content or mime-type, you only get the extension.


There are definitely other ways one can use to extract a file extension with PHP. But using a built-in function is always the right way to go.

If you like this post, please share
Notify of
Inline Feedbacks
View all comments