Wednesday 25 December 2013

How to get file extension in PHP

In PHP there are many ways to exclude a file extension such as using substr() or RegEx etc. But to use pathinfo() is the better way to deal with this.

The pathinfo() function returns an array that contains information about a path. The following array elements are returned:

Array
(
[dirname] => /directory_name (Ex. Test)
[basename] => file name (Ex. mydoc.png)
[extension] => file extension (Ex. png)
)

It has two parameters: pathinfo(path,options);
path: filepath
options:
PATHINFO_DIRNAME - return only dirname
PATHINFO_BASENAME - return only basename
PATHINFO_EXTENSION - return only extension

<?php

print_r(pathinfo("myfile.png",PATHINFO_EXTENSION));

Output: png

?>

No comments:

Post a Comment