Free Web Tutorials Free Online Tutorials About Us Contact Us

PHP File Read/Write Tutorial:


PHP Reading form a File?

In PHP it is relatively easy to read from a file.

PHP has inbuilt function called fgets() that allows us to read lines from files

Example:
fgets ($handle, $length);

As you can see from the above pseudo code fgets excepts two parameters

(1) $handle - the file pointer
(2) $length - An integer to tell the function how much data, in bytes, it is supposed to read.
(Note 1 character is the equivalent of one byte - so if we wanted to read 10 characters then we would use fread($fh, 10);)


Lets now create a sample:

<?php
$myFile = "readFile.txt";
$fh = fopen($myFile, 'r');
$outputFileContents = fread($fh, 10);
fclose($fh);

echo $outputFileContents;
?>

'R' denotes that we want to open the file in read mode.

The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

In PHP if you wanted to read all data that is stored in a file, then you need to get the size of the file. The filesize function returns the length of a file, in bytes.

<?php
$myFile = "readFile.txt";
$fh = fopen($myFile, 'r');
$fs=filesize($myFile);
$outputFileContents = fread($fh, $fs);
fclose($fh);
echo $outputFileContents;
?>

Another way is too loop through the contents of the file line by line until you reach the end of the file

<?php
$file = "readFile.txtt";
$fp = fopen($file, "r");
while(!feof($fp)) {
	$outputFileContents = fgets($fp, 2024);
	echo "$outputFileContents 
"; } fclose($fp); ?>

free online unix tutorial