How do I read a file using PHP?
The following are basic steps followed in reading a file using PHP
Open a file using fopen
lock the file using flock
read the contents of the file using fread
unlock the file using flock
close the file using fclose
$filename = "../example/file.txt"; //name of file
$handle = fopen($filename, "r"); //open the file using fopen
flock($handle,LOCK_SH);//lock the file using shared lock for reading
$contents = fread($handle, filesize($filename));//read the file using fread
echo $contents; //display the contents of file
fclose($handle);//close the file using fclose
1. The first line of the code specifies name of the file.
2. Then open the file using fopen
in "r" read mode. If the file doesn't exists, it will show you an error.
3.Lock the file using flock
.using an shared lock,which is set by putting LOCK_SH.When a statement reads data without making any modifications, its transaction obtains a shared lock on the data.
4.Read the data from the file using fread
. Read the file until end of the file will be reached.
5.unlock the file using flock
by putting LOCK_UN
6.close the file using fclose