How to get the file extension in PHP 5
Obtaining the the file extension out of a file name – Edit content (add a revision)
`section(title:'Get a file extension in PHP') There are moments when you need to find the extension of a certain file (for example after doing a file upload -`tutorial(name:'File uploads in PHP')-, you want to see if the uploaded file matches your allowed extensions). It is pretty simple to do this using the next function which accepts as an input parameter a full path or only the filename and returns the file extension. The algorithm is this : it checks for the character '.' (dot) and if it doesn't find it then it means our file doesn't have any extension. In case it finds the '.' (dot) character then it returns in lowercase all the text after the last dot. `code(lang:'php' version:'5.2') {` function getFileExtension($filePath){ if (strpos($filePath,'.') === false){ return ''; } return strtolower(substr(strrchr($filePath, '.'), 1)); } `} The function above works even for getFileExtension("name.example.txt"), because the strrchr function returns the rightmost occurrence of the searched dot character. `section(title:'Using pathinfo()') You can also use the `a(href:'http://it.php.net/manual/en/function.pathinfo.php' content:'pathinfo()') function, described in the PHP manual. `code(lang:'php' version:'5.2') {` $originalFileName = 'example.file.txt'; $fileExtension = ''; $info = pathinfo($originalFileName); if (isset($info['extension'])) $fileExtension = $info['extension']; print $fileExtension; `}
Save as new Revision
Syntax docs