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
PHPcode:
<?php
$filename = "../example/file.txt";
$handle = fopen($filename, "r");
flock($handle,LOCK_SH);
$contents = fread($handle, filesize($filename));
echo $contents;
flock($handle,LOCK_UN);
fclose($handle);
?>
Step:1
$filename = "../example/file.txt";
The above line of the code specifies name of the file.
Step:2
$handle = fopen($filename, "r");
By using fopen we can open the file and “r” is for read mode. If the file doesn't exists, it will show
you an error
Step:3
flock($handle,LOCK_SH);
flock is used for LOCK the file .By 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.
Step:4
$contents = fread($handle, filesize($filename));
By using fread we can read the data from the file. Read the file until end of the file will be reached.
step:5
flock($handle,LOCK_UN);
We can unlock the file by using flock ( LOCK_ UN )
step:6
fclose($handle);
We can close the file by using fclose |