There are two useful methods to read files with PHP, that will be covered in this PHP Tutorial. The first method is using the fread function, this method requires a combination of the functions: fopen, fread, and fclose functions. The file_get_contents function is used in the second method that will be covered – it eliminates the need to call multiple functions to read a file in PHP.
When using both of the methods covered in this PHP Tutorial, the file will be read to a string – this can be saved in a variable for later use – reading files into variables is not always necessary, sometimes you can use the returned data from the file directly.
Read file in PHP – the Fread Function
As was mentioned earlier, the fread function uses a combination of: fopen, fread, and fclose. The file is first opened for reading using fopen with the r mode – this mode will open the file for reading, and place the pointer at the beginning of the file.
<?php $filename = "My-File.txt"; $filesize = filesize($filename); $handle = fopen($filename, "r"); $contents = fread($handle, $filesize); fclose($handle); echo $contents; ?>
The second argument in the fread function, is the number of bytes where we want PHP to stop reading – in this case, the file size of the file we are going to read.
Get Content of file in PHP - the File_get_contents Function
Using the file_get_contents function to read files with may be easier than using fread and its accompanied functions.
<?php $file = "my-beloved-text-file.txt"; $FileContent = file_get_contents($file) echo $FileContent; ?>