Get File Extension with PHP's Underappreciated Tool: pathinfo()
Getting a file's extension in PHP has sparked numerous web discussions, yielding a wide range of solutions. However, there's often a forgotten gem: pathinfo().
Unlike languages with built-in extension functions, PHP's pathinfo() provides this functionality with a concise yet powerful command:
$ext = pathinfo($filename, PATHINFO_EXTENSION);
This method has the advantage of being built-in to PHP, avoiding the need for external libraries. It also empowers you to extract other path information such as the canonical path by passing different constants to the function.
For non-ASCII characters, it's necessary to first set the locale, as demonstrated below:
setlocale(LC_ALL, 'en_US.UTF-8');
Note that pathinfo() solely focuses on the extension and doesn't consider file content or MIME type. It also operates on file paths, unlike PARSE_URL, which caters to URL resources paths.
This forgotten gem, pathinfo(), is a convenient and comprehensive tool that simplifies the task of getting a file's extension in PHP. Its efficiency and built-in nature make it an ideal choice for a wide range of applications.
The above is the detailed content of How Can PHP's `pathinfo()` Function Efficiently Retrieve a File's Extension?. For more information, please follow other related articles on the PHP Chinese website!