必须用 stream_context_create() 配合 file_get_contents(),因其默认 HTTP 流封装器无超时、无 User-Agent、不重定向、不支持 Cookie;通过 context 可精确控制请求行为,且无需引入 cURL。
直接用 file_get_contents() 远程访问 HTTP/HTTPS 文件,默认不支持自定义请求头、超时、重定向控制或 Cookie 管理——它会按 PHP 默认的 http 流封装器行为走,经常卡住、返回空、或被目标服务器拒绝。
stream_context_create() 配合 file_get_contents()
因为默认上下文太“傻”:无超时(可能阻塞几十秒)、无 User-Agent(很多站点直接 403)、不跟随重定向(301/302 返回原始响应而非最终内容)、不传 Cookie 或认证头。加 context 是唯一可控方式,且无需引入 cURL。
file_get_contents() 的第三个参数必须是 stream_context_create($options) 返回的资源$options 是二维数组:['http' => [...]],不是 ['http' => [...], 'https' => [...]] —— HTTPS 复用 http 配置即可method,不是 Method),否则静默失效file_get_contents() 远程 GET 请求最简可用配置以下配置能解决 80% 的“打不开远程文件”问题:设超时、加 UA、允许重定向、忽略 SSL 验证(仅限测试)
$context = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => 5,
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n",
'max_redirects' => 3,
'ignore_errors' => false,
],
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
],
]);
$content = file_get_contents('https://example.com/data.json', false, $context);
timeout 单位是秒,浮点数也支持(如 2.5),但低于 1 秒可能被底层截断header 中换行必须用 \r\n,不能只用 \n,否则请求头格式错误verify_peer => false 仅用于开发;生产环境应配 cafile 路径并保持 true
改 method 和 content,用 http_build_query() 拼 body,Header 写进 header 字段
$data = ['key' => 'value', 'token' => 'abc'];
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Cookie: sessionid=xyz123;\r\n" .
"Authorization: Basic " . base64_encode('user:pass') . "\r\n",
'content' => http_build_query($data),
'timeout' => 8,
],
]);
$response = file_get_contents('https://api.example.com/submit', false
, $context);
content 是 raw body 字符串,不是数组;http_build_query() 必须手动调用header 字符串,不能单独设 cookie 键Content-type 改成 application/json,content 改为 json_encode($data)
返回 false 但没报错?开启错误报告看真实原因:
ini_set('display_errors', '1');
error_reporting(E_ALL);
var_dump(file_get_contents('http://...', false, $context)); // false 时查 error_get_last()
failed to open stream: Connection timed out → 检查 timeout 值和网络连通性,别设 0SSL operation failed → ssl.verify_peer 设 false 临时绕过(仅调试),或补全 cafile
403 Forbidden → 确认 User-Agent 不为空,有些站还校验 Accept 头get_headers($url, true, $context) 先看响应头是否含 Content-Length: 0 或重定向未生效真正难的不是写 context 数组,而是理解每个选项在 HTTP 协议层的实际作用——比如 max_redirects 控制的是流封装器内部重试,不是 curl 的 -L;ignore_errors 影响的是函数是否返回 false,而不是是否抛异常。这些细节不验证就容易反复踩坑。