Now that we know how to open and close files, let’s take a look at how to read them. To demonstrate how this works, let’s say we have a file called
real-cool-file.txt with the following text:
First, we’ll need to open the file in read mode:
$cool_file = fopen("real-cool-file.txt", "r");
Then, we can use the
fread function to read the file:
$cool_text = fread($cool_file, 4);
fread function reads the given number of bytes from a file, returning the result as a string. Let’s take a closer look at how it works:
- The first argument,
$cool_file, is the file pointer for the file we’d like to read.
- The second argument,
4, is the number of bytes we’d like to read from the file. A byte is a unit of data stored on a computer. In this case, it is equivalent to one character of text.
Our code reads 4 bytes of text from
$cool_text. If we were to then
echo $cool_text, here’s what we would see in the console:
Since we read only the first 4 bytes, we’re seeing only the first 4 characters of the file. But, what about the rest? For
real-cool-file.txt, we can count that the file contains 8 characters, meaning that we can read the entire file by reading 8 bytes:
$cool_text = fread($cool_file, 8); echo $cool_text; // Wowsers!
However, in practice, we won’t always know the exact number of bytes to read. We might work with files of varying sizes or with files that are too large to count manually. Fortunately, PHP gives us the
filesize function to find out the size of any file. Here’s how:
$cool_size = filesize("real-cool-file.txt");
filesize function takes a file name as an argument, returning the size of the file in bytes. In this example, we used
filesize to find the size of
real-cool-file.txt and store the result in
$cool_size. We can then use this variable with
fread to read the entire file, even if we didn’t know the number of bytes to read in advance:
$cool_text = fread($cool_file, $cool_size); echo $cool_text; // Wowsers!
When we’re finished reading the file, we’ll close it with the
Now, it’s your turn! Let’s practice reading a file in PHP.
We have a file,
welcome.txt, that we’d like to read. To start, open the file in read mode. Store the file pointer in a new variable,
Before we can read
welcome.txt, we’ll need to know how many bytes to read. Create a new variable,
$size, and set it to the file size of
Next, read the contents of
welcome.txt into a new variable,
To find out what’s in the file, echo
$welcome_text to the console.
Now that we’re done, close