Get a file extension, very useful for a file uploader.
function getExtension($file) {
$pos = strrpos($file, '.');
if(!$pos) {
return 'Unknown Filetype';
}
$str = substr($file, $pos, strlen($file));
return $str;
}
First check for a dot '.' which would mean a valid file extension, if one is not found return "Unknown Filetype" and exit the function. Assuming we now found a dot in the file name we can move on to grabbing the actual file extension.
We achieve this using substr(). The first argument is the file name, the second is the position of the last dot, and the third argument is file name length.
The last step is to return that file extension to be used in whatever part of our script we need.
Here is a quick code snippet/example.
$ext = getExtension('mycoolfile.swf');
switch($ext) {
case 'php' :
print "File is a PHP file";
break;
case 'jpg' :
print "File is a JPEG";
break;
case 'swf' :
print "File is an SWF or Flash format.";
break;
}