Here I’ll give some file reading examples. There’s a few different ways to do this. I’m going to focus on plain text files only, as opposed to binary files.
If you just want to read the contents of a file into a string variable, then the easiest thing to do is use $mystring = file_get_contents(”/home/adam/myfile”);
For more control over what you’re doing, or if you want to do anything more than reading a file into a string, you’ll need to use the fopen, fread and fclose functions.
To read everything in one go:
<?php
$myfile = “/home/adam/myfile”;
$file_handle = fopen($myfile, “r”); //Open /home/adam/myfile for READING
$data = fread($file_handle, filesize($myfile));
echo “File contains: ” . $data . “\n”;
fclose($file_handle);
?>
In this case, we use the filesize() function to get size in bytes of $myfile, and we pass that value to fread() as the number of bytes to read from the file, i.e. the entire file.
You could replace filesize() with a fixed figure, or alternatively, if you want to keep reading until you find a certain character or string;
<?php
$myfile = “/home/adam/myfile”;
$mysize = filesize($myfile);
$file_handle = fopen($myfile, “r”);
while (strpos($tmpdata, “FINDME”) === false)
{
$tmpdata = fread($file_handle, 128);
$data .= $tmpdata;
}
fclose($file_handle);
….
Now at this point, we’re reading 128 bytes of the file at a time until we find “FINDME”. Depending on the size of the file, pick a reasonable figure. The lower the figure, the more times the loop has to run, which is inefficient in itself, the larger figure Chances are though, we’ll end up with additional data after “FINDME” anywhere between 0 and 122 characters. If we don’t want that, to remove “FINDME” and anything after it:
….
$data = substr ($data, 0, strpos($data, “FINDME”) );
?>
You should also be checking the return code of fopen to ensure that it has actually returned a valid file handle as opposed to blindly reading from what may be an invalid handle.
Edit:
Reader Brian makes a valid point, that the fread(…, 128) could cut off “FINDME” in which case, it will never match, we should perform our test against the data just read as well as the data in the previous read:
while (strpos($tmpdata_last . $tmpdata, “FINDME”) === false)
{
$tmpdata_last = $tmpdata;
$tmpdata = fread($file_handle, 128);
$data .= $tmpdata;
}
Tags: fclose, filesize, file_get_contents, fopen, fread, PHP, php programmer, strpos, substr
I’m a bigger fan of fgets then fread as it seems like most of the time you are searching for a line that contains a string. also if the string you are looking for is split between two of your fread calls you might not find the needle in your haystack as you don’t combine the current line and the last one to see if it to chopped between the two.