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
:
file_exists("reed-me.txt"); // false file_exists("read-me.txt"); // true
The 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 false
otherwise.
Some other common file information functions include: filetype
, fileperms
, and is_dir
. The full list of available functions is available in the official PHP documentation.
To get a feel for how file information operations work, let’s practice using file_exists
!
Instructions
The $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 file_exists
on $name
.
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 "hello.txt"
instead.