file_get_contents
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
file_get_contents — 将整个文件读入一个字符串
说明
string
$filename
,bool
$use_include_path
= false
,?resource
$context
= null
,int
$offset
= 0,?int
$length
= null
): string|false
和 file() 一样,只除了
file_get_contents() 把文件读入一个字符串。将在参数
offset
所指定的位置开始读取长度为
length
的内容。如果失败,file_get_contents()
将返回 false
。
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。
注意:
如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。
参数
filename
-
要读取的文件的名称。
use_include_path
-
注意:
常量
FILE_USE_INCLUDE_PATH
用于触发搜索 include path。 因为FILE_USE_INCLUDE_PATH
是个 int,如果开启了严格类型 将无法启用。 所以要用true
来代替常量。 context
-
stream_context_create() 创建的有效的上下文(context)资源。 如果你不需要自定义 context,可以用
null
来忽略。 offset
-
读取原始数据流的开始位置偏移量。负的 offset 会从数据流的末尾开始统计。
远程文件不支持偏移量寻址(
offset
)。 对远程文件以较小的 offset 可能可以正常寻址, 但由于是对缓冲流进行操作,所以操作结果不可预测。 length
-
要读取数据的最大长度。 默认情况下会读到文件末尾。 注意,该参数会应用到处理 stream 的过滤器(filter)中。
返回值
函数返回读取到的数据, 或者在失败时返回 false
。
错误/异常
以下情况会导致 E_WARNING
级别错误:
无法找到 filename
文件;
length
小于零;
在 steam 中无法寻址偏移量 offset
。
Windows 下用 file_get_contents() 读取目录会导致 E_WARNING
错误。
PHP 7.4 起,其他操作系统也会出现同样错误。
更新日志
版本 | 说明 |
---|---|
8.0.0 |
现在 length 允许为 null。
|
7.1.0 |
支持负数 offset 。
|
示例
示例 #1 获取并输出网站首页 HTML 源码
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
示例 #2 在 include_path 里搜索
<?php
// 如果开启了严格类型,例如 declare(strict_types=1);
$file = file_get_contents('./people.txt', true);
// 否则就这样写
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
示例 #3 读取文件一小节
<?php
// 从第 21 个字符开始,读取 14 字符长度
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>
以上示例的输出类似于:
string(14) "lle Bjori Ro"
示例 #4 使用 stream 上下文(context)
<?php
// 创建 stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// 以下面设置的 HTTP 头来打开文件
$file = file_get_contents('http://www.example.com/', false, $context);
?>
注释
注意: 此函数可安全用于二进制对象。
如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议,注意其用法及其可提供的预定义变量。
使用 SSL 时,Microsoft IIS
会违反协议不发送 close_notify
标记就关闭连接。PHP 会在到达数据尾端时报告“SSL: Fatal Protocol Error”。
要解决此问题,error_reporting 应设定为降低级别至不包含警告。PHP
4.3.7 及更高版本可以在使用 https://
包装器打开流时检测出有问题的 IIS 服务器软件 并抑制警告。在使用
fsockopen() 创建 ssl://
套接字时,开发者需检测并抑制此警告。
参见
- file() - 把整个文件读入一个数组中
- fgets() - 从文件指针中读取一行
- fread() - 读取文件(可安全用于二进制文件)
- readfile() - 输出文件
- file_put_contents() - 将数据写入文件
- stream_get_contents() - 读取资源流到一个字符串
- stream_context_create() - 创建资源流上下文
- $http_response_header
用户贡献的备注 6 notes
file_get_contents can do a POST, create a context for that first:
<?php
$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);
?>
To prevent mixed content most browsers/functions will use the protocol already used if you specify only // instead of http:// or https://. This is not the case with file_get_contents. You must specify the protocol.
This does not work:
<?php
$jsonData = file_get_contents('//example.com/file.json');
print $jsonData;
?>
Specifying only 'example.com/file.json' without the double slash does not work either.
When running on Apache 2.4 , using $_SERVER['REQUEST_SCHEME'] is a better way to be protocol agnostic.
<?php
$jsonData = file_get_contents($_SERVER['REQUEST_SCHEME'].'://example.com/file.json');
print $jsonData;
?>
If using another web server, you may have to get the protocol another way or hard code it.
If doing a negative offset to grab the end of a file and the file is shorter than the offset, then file_get_contents( ) will return false.
If you want it to just return what is available when the file is shorter than the negative offset, you could try again.
For example...
$contents = file_get_contents( $log_file, false, null, -4096 ); // Get last 4KB
if ( false === $contents ) {
// Maybe error, or maybe file less than 4KB in size.
$contents = file_get_contents( $log_file, false, null );
if ( false === $contents ) {
// Handle real error.
}
}
See also: http_get_last_response_headers() function to get last HTTP response headers including the HTTP response status code (200, 404, ...)
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:
<?php
$data = file_get_contents('https://example.net/some-link');
$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
}
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.
备份地址:http://www.lvesu.com/blog/php/function.file-get-contents.php