File Information
File information is the set of facts a program can check about a file. Small PHP functions answer checks like whether a file exists and how big it is.
A file that exists and one that does not
The setup line writes a real file. The two var_dump lines show true for the written file and false for a missing name.
<?php
file_put_contents("note.txt", "Hello\n");
var_dump(file_exists("note.txt"));
var_dump(file_exists("missing.txt"));An exact size in bytes
The saved text holds eleven letters and spaces plus one newline. The filesize line prints 12, the exact byte count of that fixed content.
<?php
file_put_contents("size.txt", "Hello files\n");
echo filesize("size.txt"), "\n";The parts of a path
A path is the text that names where a file sits. pathinfo breaks one path into its parts, and basename picks out the file name part.
<?php
$path = "notes/report.txt";
print_r(pathinfo($path));
echo basename($path), "\n";Example
<?php
file_put_contents("report.txt", "Report ready\n");
var_dump(file_exists("report.txt"));
echo filesize("report.txt"), "\n";
var_dump(is_file("report.txt"));
var_dump(is_dir("report.txt"));Key points
- file_exists reports whether a name exists.
- filesize gives the size of a file in bytes.
- A byte is a unit for the size of data, and one plain text character takes one byte.
- is_file reports whether a name is a regular file.
- is_dir reports whether a name is a folder.
- basename gives the last part of a path.
In this example, the program writes one report file and then checks it three ways. file_exists answers true, filesize prints 13 for the thirteen bytes saved, and is_file answers true while is_dir answers false.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does filesize give for a file?