Current Location: Home> Latest Articles> PHP File Reading Methods Explained: file_get_contents vs fread with Code Examples

PHP File Reading Methods Explained: file_get_contents vs fread with Code Examples

gitbox 2025-08-05

Overview of File Reading in PHP

Reading file content is a common task in PHP development, whether you're working with local text files or remote resources. PHP offers several functions for this purpose, with file_get_contents and fread being the most widely used. This article explains both methods in detail with practical examples to help you quickly master file reading techniques.

Reading Files Using file_get_contents

The file_get_contents function provides a simple and direct way to read an entire file's contents into a string. It's ideal for quickly accessing small to medium-sized files in one go.

$file_contents = file_get_contents('file.txt');
echo $file_contents;

In the example above, file_get_contents reads the contents of file.txt and outputs it.

Reading Remote Files

Besides local files, file_get_contents can also retrieve content from remote URLs. Simply pass the full URL as a parameter.

$file_contents = file_get_contents('http://www.example.com/file.txt');
echo $file_contents;

This example fetches and displays the content of a text file hosted on a remote server.

Reading Binary Files

You can also use file_get_contents to read binary files, such as images, by adjusting the parameters accordingly.

$file_contents = file_get_contents('image.png', true);
echo $file_contents;

By setting the second parameter, the function can be instructed to handle binary content appropriately.

Reading Files Using fread

fread offers more control and flexibility compared to file_get_contents. It's useful for working with large files or situations where you need to read data in chunks.

$file_handle = fopen('file.txt', 'r');
$file_size = filesize('file.txt');
$file_contents = fread($file_handle, $file_size);
fclose($file_handle);
echo $file_contents;

In this example, the file is opened using fopen, its size is determined with filesize, and fread reads the content. The file is then closed with fclose.

Reading Files Line by Line

If you need to process a file line by line, fgets is a suitable choice. It can be used in a loop to read each line individually.

$file_handle = fopen('file.txt', 'r');
while (!feof($file_handle)) {
    $line = fgets($file_handle);
    echo $line;
}
fclose($file_handle);

This code reads and outputs the file line by line, making it suitable for processing logs or large text files.

Conclusion

PHP offers flexible options for reading file content. Use file_get_contents when you need a quick and easy way to get the entire content of a file. For more controlled or partial reading—especially with large files—fread is a better choice. Choose the method that best suits your specific use case to write efficient and maintainable code.