I wish to get the file extension of an image I am uploading, but I just get an array back.
$userfile_name = $_FILES['image']['name'];
$userfile_extn = explode(".", strtolower($_FILES['image']['name']));
Is there a way to just get the extension itself?
There are a few different ways to extract the extension from a filename with PHP, which is given below: Using pathinfo() function: This function returns information about a file. If the second optional parameter is omitted, an associative array containing dirname, basename, extension, and the filename will be returned.
The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string. By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file.
Use pathinfo() Function to Get File Extension in PHP This function extracts the path information from the given path. The correct syntax to use this function is as follows. It is the string containing the path with file name and extension. We will extract path info from this string .
No need to use string functions. You can use something that's actually designed for what you want: pathinfo()
:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
This will work as well:
$array = explode('.', $_FILES['image']['name']);
$extension = end($array);
A better method is using strrpos + substr (faster than explode for that) :
$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);
But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With