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.
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));php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.