How can I read the contents of a file with PHP?
PHP has many file-related functions, and there are a variety of ways to use this scripting language’s file i/o capabilities to read the contents of a file. Here are a few different ways to get this task done:
file_get_contents
The easiest and most recommended way to read a file’s contents into a string is the file_get_contents function. Its only required parameter is the filename, whose contents it returns in a string.
<?php
// Read the contents of myfile.txt into a variable.
$fileContents = file_get_contents('myfile.txt');
?>
file
The file function is similar to file_get_contents in that it reads and returns the entire contents of a file. It differs in that its return value is an array with each line of the file as a separate element.
<?php
$lines = file('myfile.txt');
for ($i = 0; $i < count($lines); $i++) {
// Label and print each line from the file.
printf("Line %d: %s\n", $i, $lines[$i]);
}
?>
A trick some programmers use with the file function is to pass its output as a parameter to the implode function, gluing together all the array elements into a single string containing the file's contents.
<?php
// Read the contents of myfile.txt into a variable.
$fileContents = implode('', file('myfile.txt'));
?>
This has the same result as assigning the return value of file_get_contents to a variable.
fopen, fread
You may want to explicitly open, read and close your input file. If so, here is how it's done:
<?php $file = 'myfile.txt'; $fp = fopen($file, 'r'); $fileContents = fread($fp, filesize($file)); fclose($fp); ?>
The second parameter to fread is a length in bytes. The fread function will stop reading if it reaches that point. Using fread is not as efficient as file_get_contents, and is really more useful when you must read binary files.




