How to Retrieve File Extensions in PHP
Problem:
You aim to extract the file extension from an image upload, but you encounter an array response instead of the desired extension.
Example Code:
$userfile_name = $_FILES['image']['name']; $userfile_extn = explode(".", strtolower($_FILES['image']['name']));
Issue:
The above code returns an array, not the sole extension.
Solution:
PHP provides a convenient function specifically designed for this purpose: pathinfo().
$path = $_FILES['image']['name']; $ext = pathinfo($path, PATHINFO_EXTENSION);
This code snippet utilizes the pathinfo() function to extract the file extension from the given file path in the $path variable. The PATHINFO_EXTENSION constant instructs the function to retrieve the extension specifically. The result is stored in the $ext variable.
The above is the detailed content of How to Extract File Extensions in PHP: Why pathinfo() is Your Best Friend. For more information, please follow other related articles on the PHP Chinese website!