By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Read Files With PHP

How to read local files with Fread and File_get_contents in PHP.

Edited: 2014-12-28 04:07

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.

$filename = "My-File.txt";
$filesize = filesize($filename);
$handle = fopen($filename, "r");
$contents = fread($handle, $filesize);
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.

$file = "my-beloved-text-file.txt";
$FileContent = file_get_contents($file)

echo $FileContent;

See also

  1. Creating and Writing to Files
  2. Deleting Files and Directories
  3. Copying Files
  4. Renaming Files