PHP Getting file information


Check if a path is a directory or a file

The is_dir function returns whether the argument is a directory, while is_file returns whether the argument is a file. Use file_exists to check if it is either.

$dir  = "/this/is/a/directory";
$file = "/this/is/a/file.txt";

echo is_dir($dir) ? "$dir is a directory" : "$dir is not a directory", PHP_EOL,
    is_file($dir) ? "$dir is a file" : "$dir is not a file", PHP_EOL,
    file_exists($dir) ? "$dir exists" : "$dir doesn't exist", PHP_EOL,
    is_dir($file) ? "$file is a directory" : "$file is not a directory", PHP_EOL,
    is_file($file) ? "$file is a file" : "$file is not a file", PHP_EOL,
    file_exists($file) ? "$file exists" : "$file doesn't exist", PHP_EOL;

This gives:

/this/is/a/directory is a directory
/this/is/a/directory is not a file
/this/is/a/directory exists
/this/is/a/file.txt is not a directory
/this/is/a/file.txt is a file
/this/is/a/file.txt exists

Checking file type

Use filetype to check the type of a file, which may be:

  • fifo
  • char
  • dir
  • block
  • link
  • file
  • socket
  • unknown

Passing the filename to the filetype directly:

echo filetype("~"); // dir

Note that filetype returns false and triggers an E_WARNING if the file doesn't exist.

Checking readability and writability

Passing the filename to the is_writable and is_readable functions check whether the file is writable or readable respectively.

The functions return false gracefully if the file does not exist.

Checking file access/modify time

Using filemtime and fileatime returns the timestamp of the last modification or access of the file. The return value is a Unix timestamp -- see Working with Dates and Time for details.

echo "File was last modified on " . date("Y-m-d", filemtime("file.txt"));
echo "File was last accessed on " . date("Y-m-d", fileatime("file.txt"));

Get path parts with fileinfo

$fileToAnalyze = ('/var/www/image.png');

$filePathParts = pathinfo($fileToAnalyze);

echo '<pre>';
echo '</pre>';

This example will output:

    [dirname] => /var/www
    [basename] => image.png
    [extension] => png
    [filename] => image

Which can be used as:

$pathThe full path of the file to be parsed
  • If an option (the second parameter) is not passed, an associative array is returned otherwise a string is returned.
  • Does not validate that the file exists.
  • Simply parses the string into parts. No validation is done on the file (no mime-type checking, etc.)
  • The extension is simply the last extension of $path The path for the file image.jpg.png would be .png even if it technically a .jpg file. A file without an extension will not return an extension element in the array.