PHP Read File
Summary: in this tutorial, you’ll learn how to read a file using the various built-in PHP functions.
To read the contents from a file, you follow these steps:
- Open the file for reading using the fopen() function.
- Read the contents from the file using the fread() function.
- Close the file using the fclose() function.
Here’s the syntax of the fread() function:
fread ( resource $stream , int $length ) : string|false
Code language: PHP (php)
The fread() function has two parameters:
- The $stream is a file system pointer resource, which is typically the result of the fopen() function.
- The $length specifies the maximum number of bytes to read. If you want to read the entire file, you can pass the file size to the $length parameter.
The fread() function returns the file contents or false if it fails to read.
The fread() function stops reading the file once the $length number of bytes has been read or the end of file (EOF) has been reached.
To check if the file pointer is at end of file, you can pass it to the feof() function:
feof ( resource $stream ) : bool
Code language: PHP (php)
The feof() function returns true if the $stream is at the EOF or an error occurs. Otherwise, it returns false .
To read a file line by line, you use the fgets() function:
fgets ( resource $handle , int $length = ? ) : string|false
Code language: PHP (php)
Like the fread() function, the fgets() function accepts a file system pointer resource and up to a number of bytes to read. If you omit the $length argument, the fread() function will read the entire line.
PHP read file examples
Let’s take some examples of how to read a file.
1) Read the entire file into a string
Suppose that you have a file named population.txt located at public directory with the following contents:
1 New York New York 8,253,213 2 Los Angeles California 3,970,219 3 Chicago Illinois 2,677,643 4 Houston Texas 2,316,120 5 Phoenix Arizona 1,708,127 6 Philadelphia Pennsylvania 1,578,487 7 San Antonio Texas 1,567,118 8 San Diego California 1,422,420 9 Dallas Texas 1,343,266 10 San Jose California 1,013,616
Code language: plaintext (plaintext)
The following example uses the fread() function to read the contents of the entire population.txt file into a string and shows it on the webpage:
$filename = './public/population.txt'; $f = fopen($filename, 'r'); if ($f) < $contents = fread($f, filesize($filename)); fclose($f); echo nl2br($contents); >
Code language: HTML, XML (xml)
First, open the population.txt file using the fopen() function:
$f = fopen($filename, 'r');
Code language: PHP (php)
Second, read the contents of the entire file using the fread() function; use the filesize() function to get the size of the file:
$contents = fread($f, filesize($filename));
Code language: PHP (php)
Third, show the contents of the file on a web page; use the nl2br() function to convert the newline characters to
tags.
echo nl2br($contents);
Code language: PHP (php)
Finally, close the file using the fclose() function.
Note that the file_get_contents() function is a shortcut for opening a file, reading the whole file’s contents into a string, and close it.
2) Read some characters from a file
To read some characters from a file, you specify the number of bytes to read. The following example uses the fread() function to read up to 100 bytes from the population.txt file:
$filename = './public/population.txt'; $f = fopen($filename, 'r'); if ($f) < $contents = fread($f, 100); fclose($f); echo nl2br($contents); >
Code language: HTML, XML (xml)
1 New York New York 8,253,213 2 Los Angeles California 3,970,219 3 Chicago Illinois 2,677,64
Code language: plaintext (plaintext)
3) Read a file line by line
The following example uses the fgets() funtion to read the population.txt file line by line:
$filename = './public/population.txt'; $lines = []; $f = fopen($filename, 'r'); if (!$f) < return; > while (!feof($f)) < $lines[] = fgets($f); >print_r($lines); fclose($f);
Code language: HTML, XML (xml)
Summary
- Use the fread() function to read some or all contents from a file.
- Use the fgets() function to read a line from a file.
- Use the feof() function to test the end-of-file has been reached.
- Use the filesize() function to get the size of the file.
file_get_contents
This function is similar to file() , except that file_get_contents() returns the file in a string , starting at the specified offset up to length bytes. On failure, file_get_contents() will return false .
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
Note:
If you’re opening a URI with special characters, such as spaces, you need to encode the URI with urlencode() .
Parameters
Note:
The FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. This is not possible if strict typing is enabled, since FILE_USE_INCLUDE_PATH is an int . Use true instead.
A valid context resource created with stream_context_create() . If you don’t need to use a custom context, you can skip this parameter by null .
The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.
Seeking ( offset ) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.
Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.
Return Values
The function returns the read data or false on failure.
This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Errors/Exceptions
An E_WARNING level error is generated if filename cannot be found, length is less than zero, or if seeking to the specified offset in the stream fails.
When file_get_contents() is called on a directory, an E_WARNING level error is generated on Windows, and as of PHP 7.4 on other operating systems as well.
Changelog
Version | Description |
---|---|
8.0.0 | length is nullable now. |
7.1.0 | Support for negative offset s has been added. |
Examples
Example #1 Get and output the source of the homepage of a website
Example #2 Searching within the include_path
// If strict types are enabled i.e. declare(strict_types=1);
$file = file_get_contents ( ‘./people.txt’ , true );
// Otherwise
$file = file_get_contents ( ‘./people.txt’ , FILE_USE_INCLUDE_PATH );
?>?php
Example #3 Reading a section of a file
// Read 14 characters starting from the 21st character
$section = file_get_contents ( ‘./people.txt’ , FALSE , NULL , 20 , 14 );
var_dump ( $section );
?>?php
The above example will output something similar to:
Example #4 Using stream contexts
// Create a stream
$opts = array(
‘http’ =>array(
‘method’ => «GET» ,
‘header’ => «Accept-language: en\r\n» .
«Cookie: foo=bar\r\n»
)
);
?php
$context = stream_context_create ( $opts );
// Open the file using the HTTP headers set above
$file = file_get_contents ( ‘http://www.example.com/’ , false , $context );
?>
Notes
Note: This function is binary-safe.
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as «SSL: Fatal Protocol Error» when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.
See Also
- file() — Reads entire file into an array
- fgets() — Gets line from file pointer
- fread() — Binary-safe file read
- readfile() — Outputs a file
- file_put_contents() — Write data to a file
- stream_get_contents() — Reads remainder of a stream into a string
- stream_context_create() — Creates a stream context
- $http_response_header
User Contributed Notes 6 notes
file_get_contents can do a POST, create a context for that first:
$opts = array( ‘http’ =>
array(
‘method’ => ‘POST’ ,
‘header’ => «Content-Type: text/xml\r\n» .
«Authorization: Basic » . base64_encode ( » $https_user : $https_password » ). «\r\n» ,
‘content’ => $body ,
‘timeout’ => 60
)
);
$context = stream_context_create ( $opts );
$url = ‘https://’ . $https_server ;
$result = file_get_contents ( $url , false , $context , — 1 , 40000 );
Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.
There’s barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you’re expecting an image you can do this:
$mimetype = null ;
foreach ( $http_response_header as $v ) if ( preg_match ( ‘/^content\-type:\s*(image\/[^;\s\n\r]+)/i’ , $v , $m )) $mimetype = $m [ 1 ];
>
>
if (! $mimetype ) // not an image
>
if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)
//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null) if(!file_exists($path)) return false;
$size=filesize($path);
if($start <0) $start+=$size;
if($length===null) $length=$size-$start;
return file_get_contents($path, false, null, $start, $length );
>
I’m not sure why @jlh was downvoted, but I verified what he reported.
>>> file_get_contents($path false, null, 5, null)
=> «»
>>> file_get_contents($path, false, null, 5, 5)
=> «r/bin»