Reading Files in PHP: fread vs file_get_contents

This article explains how to read files in PHP using the two functions fread and file_get_contents, compares their syntax, parameters, return values, and shows practical code examples illustrating their differences and when to use each method.

php Courses
php Courses
php Courses
Reading Files in PHP: fread vs file_get_contents

This article explains two ways to read files in PHP: fread and file_get_contents, and discusses their similarities and differences.

1. Function syntax fread ( resource $handle , int $length ) : string $handle is a file pointer created by fopen().

$length specifies the number of bytes to read.

The function returns a string of length $length.

file_get_contents ( string $filename , bool $include_path = false , resource $context = null , int $offset = -1 , int $maxlen = null ) : string

$filename is the path of the file to read.

$include_path determines whether to search in the include_path defined in php.ini.

$context allows stream context options; null ignores it.

$offset sets the start position (available since PHP 5.1).

$maxlen limits the number of bytes returned.

2. Differences fread reads a specified number of bytes from a file handle, so you must manage the pointer and length; file_get_contents reads the entire file (or a portion defined by $offset/$maxlen) directly from the filename.

To read the whole file with fread, you can combine it with filesize() to obtain the file size.

Example using fread:

<?php
$filename = "./exit.txt";
$file = fopen($filename, 'r'); // use 'rb' for binary files
$file_info = fread($file, 10);
echo $file_info;
fclose($file);
?>

Output: php good b Example using file_get_contents:

<?php
$filename = "./exit.txt";
echo file_get_contents($filename);
?>

Output: php good better Knowledge is power Reading the entire file with fread and filesize():

$file_info = fread($file, filesize($filename));
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPfile-handlingfile_get_contentsfreadphp-tutorial
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.