Saturday, February 4, 2012

PHP : getFileExtension()

Stumbled upon this article at Cowburn. It's about the simple task of getting the extension of a filename.
It highlights this pretty nifty function:
return pathinfo($p, PATHINFO_EXTENSION);
In my case i needed it to handle filenames with queryline attached as well, simple fix:
function getFileExtension($p) {
 if( strpos($p,"?") != '' ) $p = substr($p, 0, strpos($p,"?") ); 
 return pathinfo($p, PATHINFO_EXTENSION);
 }

//==EXAMPLE==
wscript.echo getFileExtension("http://mysite/page.php?thefile=readme.txt")
// Outputs : 'php'

Read more on the pathinfo() on php.net

No comments:

Post a Comment