PHP Programing language

adplus-dvertising
PHP Read
Previous Home Next

In PHP we can read information from a file that we have to use i.e, the function fopen() to open the file for reading. Here's the code to read-open the file we created in the PHP File

PHP Code:

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

This file we created in the last lesson was named "firsttext.txt". Your PHP script that you are writing should reside in the same directory as "text.txt". Here are the contents of our file from File Write.

firsttext.txt Contents:
Amit 
Akash

Now that the file is open, with read permissions enabled, we can get started!

In PHP the File Read when using fread() Function

The fread function is the staple for getting data out of a file. The function requires a file handle and an integer to tell the function how much data, in bytes,i.e, 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 Code:

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

Output:

Amit

The first five characters from the firsttext.txt file are now stored inside theData. You could echo this string, theData, or write it to another file.

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 Code:

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

Output:

Amit

Note: It is all on one line because our "firsttext.txt " file did not have a tag to create an HTML line break. Now the entire contents of the testFile.txt file is stored in the string variable $theData.

In PHP how to use gets Function

In PHP also lets we read a line of data at a time from a file with the gets function. This can or cannot be useful to you, the programmer. 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.

"firsttext.txt" file is separated by new lines and we can utilize this function.

PHP Code:

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

The fgets function searches for the first occurrence of "\n" the newline character. If you did not write newline characters to your file as we have done in File Write, then this function might not work the way you expect it to.

Previous Home Next