Page 196 - Open Soource Technologies 304.indd
P. 196
Unit 11: Directories and Files
PHP Code Notes
$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘r’);
The file we created in the last lesson was named “testFile.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.
We can open a file or a URL to read by using fopen() function of PHP.
testFile.txt Contents
Floppy Jalopy
Pointy Pinto
Now that the file is open, with read permissions enabled, we can get started!
11.7.3 File Read Fread Function
The fread function is the staple 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 Code
$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘r’);
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
Display
Flopp
The first five characters from the testFile.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.
LOVELY PROFESSIONAL UNIVERSITY 191