Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers
Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers Faqs_Questions_And_Answers
Online Training In Hyderabad
Interview Questions
Action Script Questions
Accounting Questions
AJAX Interview Questions
C Language Questions
C++ Language Questions
Date Structures Questions
Date Base Questions
Desktop Publishing Questions
Data Ware Housing Questions
Hacking Interview Questions
Hibernate Interview Questions
Java Interview Questions
J2ee Interview Questions
Mainframes Questions
MIS Questions and Answers
Multimedia Career Questions
Marketing Questions
.NET Interview Questions
OOPS Questions and Answers
Open Source Questions
Oracle Apps Questions
PHP Interview Questions
People Soft Questions
Perl Scripting Questions
SAS Interview Questions
SAP Interview Questions
Seo Interview Questions
Security Interview Questions
Sql Server Interview Questions
Springs Interview Questions
Shell Scripting Questions
Testing Tools Questions
Web Sphere  Questions
Web Designing  Questions
Web Logic Server Questions
XML Questions and Answers
PHP Faqs
34 How do we  read a file using php?
Ans:

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
Page :     1 | 2 | 3 | 4 | 5
Top
Online Training from Hyderabad