Once You Know, You Newegg

Get a files extention with PHP

There are several ways determine a file extension using PHP. First is using the combination of strrpos() and substr() function like this :

$ext = substr($fileName, strrpos($fileName, ‘.’) + 1);

For example, if $fileName is my-new-house.jpg then:
strrpos($fileName, ‘.’)
The above will return the last location a dot character in $fileName which is 15.

So……
substr($fileName, strrpos($fileName, ‘.’) + 1)
equals substr($fileName, 16) which returns ‘jpg’

The second is using strrchr() and substr() :

$ext = substr(strrchr($fileName, ‘.’), 1);
strrchr($fileName) returns ‘.jpg’ so:
substr(strrchr($fileName, ‘.’), 1) equals:
substr(‘.jpg’, 1) which returns ‘jpg’.

Savvy?

Now, in PHP 5.2.0 PATHINFO_FILENAME was added! Hooray!

$FileName = pathinfo($_FILES[‘File’][‘name’], PATHINFO_FILENAME);

So…
$file = “somefile.jpg”;
$extension = pathinfo($file, PATHINFO_EXTENSION);

Returns the file extention!

So:
$path_parts = pathinfo(‘/www/htdocs/index.html’);
echo $path_parts[‘dirname’], “n”;
echo $path_parts[‘basename’], “n”;
echo $path_parts[‘extension’], “n”;
echo $path_parts[‘filename’], “n”;

Will return:
/www/htdocs
index.html
html
index

Blow is a simple function that gets the extension of a file. Simply using PATHINFO_EXTENSION will yield incorrect results if the path contains a query string with dots in the parameter names (for eg. &x.1=2&y.1=5), so this function eliminates the query string first and subsequently runs PATHINFO_EXTENSION on the clean path/url.

function extension($path) {
$qpos = strpos($path, “?”);
if ($qpos!==false) $path = substr($path, 0, $qpos);
$extension = pathinfo($path, PATHINFO_EXTENSION);
return $extension;
}

Now, what if the filename has an extra “.” in it??? Like: “some.file.jpg”

The below will reverse the filename and create a substring from it that starts after the first “.”. eg: “gpj.elif.emos”
Then we pull off the data and reverse it back!

if(!isset($path_parts[‘filename’])){
$reversed_filename = strrev( $path_parts[‘basename’] );
$path_parts[‘filename’] = strrev( substr( $reversed_filename, strpos( $reversed_filename, ‘.’ ) + 1 ) );
}

Nuff said?

Leave a Reply

Your email address will not be published. Required fields are marked *