Besides reading and writing, PHP includes several functions that can provide valuable information about a file, such as whether a file exists. For the most part, these functions take a single argument; the name of the file we’d like to learn about.
We’ve actually used a file information operation already. To read the correct number of bytes from a file, we used the
filesize function to obtain the file size in bytes:
$size = filesize("real-cool-file.txt");
Another common file information function is
file_exists("reed-me.txt"); // false file_exists("read-me.txt"); // true
file_exists function takes a file name as an argument and returns a boolean value. This value is
true if the given file name exists in the current directory, or
To get a feel for how file information operations work, let’s practice using
$name variable contains the name of a file that may or may not exist. Let’s create a script that prints the contents of the file if it exists or “file not found” otherwise.
To start, create a new variable,
$exists, and set it to the result of calling
Next, if the file exists, read the file and print its contents. Make sure to use an
if statement — we only want to read the file if we know it exists!
When we run the script, nothing is printed, so we don’t think the file exists. To confirm, use an
else statement to print
"file not found" if the file does not exist.
Now that we know for sure that
"hey.txt" doesn’t exist, let’s try a different file name. Set the
$name variable to