View Single Post
Old 08-17-2006, 11:46 AM   PM User | #10
jeyalakshmi
New Coder

 
Join Date: Jun 2006
Posts: 12
Thanks: 0
Thanked 0 Times in 0 Posts
jeyalakshmi is an unknown quantity at this point
Macintosh How do I read a file using PHP?

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
PHP Code:
<?php 
$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($handlefilesize($filename));//read the file using fread
echo $contents//display the contents of file
flock($handle,LOCK_UN);
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 flockby putting LOCK_UN
6.close the file using fclose
jeyalakshmi is offline   Reply With Quote