PHP – File Read

by Hiroshi on June 23, 2008

in File, File Manipulation

We have to use the function fopen to open the file for reading. Here’s the code to read-open the file.

PHP Code

<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
?>

PHP – File Read – fread Function

The fread function is for getting data out of a file. The function requires a file handle, which we have, and an integer to tell the function how much data, in bytes, it is supposed to read.

One character is equal to one byte. If you wanted to read the first five characters then you would use five as the integer.

<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
?>

PHP – File Read – All Data – The filesize function

If you wanted to read all the data from the file, then you need to get the size of the file. The filesize function returns the length of a file, in bytes, which is just what we need! The filesize function requires the name of the file that is to be sized up.

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

PHP – File Read – fgets Function

PHP also lets you read a line of data at a time from a file with the gets function. If you had separated your data with new lines then you could read in one segment of data at a time with the gets function.

<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>

Related Posts

Previous post:

Next post: