Problem:
May be you’re validating a file when uploading it. And, you need to know the file’s extension. Or, for any other reason you may need to know the extension.
Solution:
You can get file extension of a file in few ways. Here, you’ll see 2 different ways-
Method 1: Using pathinfo() built-in function
PHP has the built-in function pathinfo() which returns an array of useful information about the path including the file extension. All you need to do is specify the file path in the function. Let’s see the function in action-
<?php $path_parts = pathinfo('https://www.google.com/images/srpr/logo11w.png'); echo $path_parts['extension']; ?>
[wpdm_file id=35]
Output:
png
How it works:
The pathinfo() function above returns an associative array. One of its key is “extension” which returns the file extension.
If you want the pathinfo() function only returns the file extension, then mention PATHINFO_EXTENSION as the second parameter in the function and the function will return the extension as string. Let’s rewrite the above example-
<?php $path_parts = pathinfo('https://www.google.com/images/srpr/logo11w.png', PATHINFO_EXTENSION); echo $path_parts; ?>
[wpdm_file id=36]
Output:
png
Method 2: Using getExtension() method of the SplFileInfo class
To help developers solve common problems easily, PHP provides SPL(Standard PHP Library) which consists of some classes and interfaces. One of the classes is SplFileInfo which provides information about a file and the method getExtension() of this class let you know the file extension. Let’s see an example-
<?php $info = new SplFileInfo('https://www.google.com/images/srpr/logo11w.png'); echo $info->getExtension(); ?>
[wpdm_file id=37]
Output:
png
Caution: If method can be used if you’re using PHP 5.3.6 or greater.