We can use the fread function to read from a file in PHP . Using the previous example in the Writing to a file tutorial we will re-open the testfile.txt which will contain the following data.
This is string1
This is string2
This is string3
This is string4
The fread function again requires a file handle and a second parameter which is the number of bytes to read. Lets look at an example.
$file = fopen("testfile.txt","r");
$filedata = fread($file,3);
fclose($file);
echo $filedata;
This example does the following
We create a file handle called $file and open the file called testfile.txt in read mode
we create a variable called $filedata which we then store in the first 3 characters of data from the file handle
We close the file handle
We output the data to the screen.
In this case we display Thi
The following example uses the filesize example to get the size of the file and then you can output all of the data
$testfile = "testfile.txt";
$file = fopen($testfile,"r");
$filedata = fread($file,filesize($testfile));
fclose($file);
echo $filedata;
This will display all of the data in the file, a lot of code example you see will have the following for example
$filedata = fread($file,1000);
What is basically happening here is that the programmer has just put in an amount for the number of bytes to read parameter which is just a wild guess or such a large number that he knows that this will always work.
|