Saturday 21 December 2013

How to get the file extension and other information about file path in PHP

Today, we are going to see how to get the file extension and other information about file path in PHP. In order to get file extension from file path, PHP developers usually use strpos() to get the position of '.' and then by using substr() with dot position to get the file extension.

You can also use the below approach to get the file extension with minimal code.
To get file extension:

In order to get the file extension using file path, pathinfo() is used with PATHINFO_EXTENSION option. Here is the PHP code

$path = "/www/htdocs/application/config/inc.php";
$ext = pathinfo($path, PATHINFO_EXTENSION);

The above code will display the below output
php

To get other file information:

In order to get other file information such as Directory Name, File name and File name without extension. Here is the PHP Code

$path = "/www/htdocs/application/config/inc.php";
$fileinfo = pathinfo($path);

The above code will display the below array output

Array
(
    [dirname] => /www/htdocs/application/config/
    [basename] => inc.php
    [extension] => php
    [filename] => inc
)

Following are the options supported by pathinfo() function.

  • PATHINFO_DIRNAME
  • PATHINFO_FILENAME
  • PATHINFO_BASENAME

For more information, please refer the PHP Official documentation.

Hope, you enjoyed this Post.

No comments:

Post a Comment