Getting file information
suggest changeCheck 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;
If both paths exist, this prints:
/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:
fifochardirblocklinkfilesocketunknown
Pass the path to filetype:
echo filetype("/tmp"); // dir, when that path is a directory
PHP does not expand ~ to the home directory. filetype("~") looks for a file whose name is a tilde.
Note that filetype returns false and triggers an E_WARNING if the file doesn’t exist.
Checking readability and writability
is_writable and is_readable report whether the path is writable or readable.
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 pathinfo
$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 options: PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION, or PATHINFO_FILENAME |
- If the second parameter is omitted, an associative array is returned. Otherwise a string is returned.
- The function does not check that the file exists. It only splits the string. It does not check the MIME type.
- The extension is the last suffix of
$path, without the leading dot. Forimage.jpg.pngit ispng. A path with no suffix omits theextensionelement.