Getting file information

suggest change

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:

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 http://stackoverflow.com/documentation/php/425/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>';
   print_r($filePathParts);
echo '</pre>';

This example will output:

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

Which can be used as:

$filePathParts['dirname']
$filePathParts['basename']
$filePathParts['extension']
$filePathParts['filename']

Parameter | Details | —— | —— | $path | The full path of the file to be parsed | $option | One of four available options [PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME] |

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents