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:


File handling:
* Getting file information

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
27 File handling
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR