PHP File Read
Before you can read a file, it must first be opened using the fopen() function, and you must have proper permissions to write to the file, which are set when the file is opened. (See fopen)
Reading an open file is accomplished using the fread() function.
By opening the file using the read only (r) mode, we are then able to read the file:
In the file append lesson, we said the the contents of myfile.txt are as follows:
I am six feet tall.
I weigh 165lbs.
I have brown hair.
I have brown eyes.
If the file “myfile.txt” was unable to be opened, we receive the error message “myfile.txt does not exist!”.
Reading A Portion Of A File
Some files can be very large, and anytime you use the fread function to read a file, you can also specify how much of that file should be read (in bytes).
$contents = fread($file, 15);
fclose($file);
echo $contents;
In the above example, we used the fopen function to open the file “myfile.txt” with read permissions (r).
We then told the code to read the first 15 bytes (characters) of myfile.txt and assigned those contents the variable name “$contents”.
After we gathered the contents we needed, we then closed the file using the fclose() function and echoed those contents using the variable “$contents”.
By gathering and echoing the first 15 bytes of data in myfile.txt, this bit of code would display:
I am six feet t
Reading The Entire Contents Of A File
What if you want to read the entire file, and you either don’t know its exact size, or the filesize may change as your script writes to the file?
In this case, we would have the code automatically calculate the file’s entire size and gather all the information in it:
$contents = fread($file, filesize($file));
fclose($file);
echo $contents;
In this case, we opened the file with read permissions, assigned the contents a variable ($contents), calculated the entire filesize, closed the file, then lastly we echoed its contents.
This bit of code would display the entire contents of myfile.txt:
I am six feet tall.
I weigh 165lbs.
I have brown hair.
I have brown eyes.




