直接根据目标服务器是否要求特定 HTTP 头或 Cookie 来决定:无需复杂配置时,使用 file_get_contents 配合 stream_context_create 即可;需要精细控制(如自定义 Header、Cookie、超时)时,使用 cURL。

file_get_contents 的上下文配置
file_get_contents 是 PHP 内置函数,适合快速抓取。通过 stream_context_create 可以传入包含 header 和 user_agent 的数组,模拟浏览器请求。

在构建 context 时,将 http 协议的参数放入数组中。设置 method 为 GET,并在 header 中添加必要的 User-Agent 和 Accept 字段,以避免被某些服务器拦截。此方法代码量少,但处理复杂响应(如分块编码)时不如 cURL 稳定。
cURL 的多功能实现
cURL 提供了更完整的 HTTP 客户端功能。通过 curl_init 初始化会话,设置 CURLOPT_URL、CURLOPT_RETURNTRANSFER 等选项,接着用 curl_exec 执行并获取结果。

<?php
$url = 'https://example.com';
// 使用 file_get_contents
$opts = [
'http' => [
'method' => 'GET',
'header' => "User-Agent: Mozilla/5.0\r\nAccept: text/html\r\n"
]
];
$context = stream_context_create($opts);
$content1 = @file_get_contents($url, false, $context);
if ($content1 === false) {
echo "file_get_contents failed\n";
}
// 使用 cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$content2 = curl_exec($ch);
if (curl_errno($ch)) {
echo "cURL error: " . curl_error($ch) . "\n";
} else {
echo "cURL success, length: " . strlen($content2) . "\n";
}
curl_close($ch);
运行上述代码,若网络通畅,file_get_contents 会静默成功或失败(取决于错误抑制符),而 cURL 会明确输出成功后的内容长度。若遇到超时或 DNS 解析失败,cURL 会通过 curl_error 打印具体原因,便于排查。
cURL 允许设置详细的超时时间、代理、SSL 验证以及复杂的 Header。在处理重定向、POST 数据或需要保持连接复用(通过 curl_close 释放资源)的场景下,cURL 是更可靠的选择。以下代码展示了如何同时支持两种方式的简单封装逻辑。
错误处理与输出对比
在实际调用中,必须检查返回值是否为 false 或使用 curl_error 获取具体错误信息,以区分网络故障与服务器拒绝访问。
当目标网页返回非 200 状态码时,file_get_contents 可能抛出警告或返回空字符串,而 cURL 可以通过 CURLOPT_FAILONERROR 配置行为。对于大文件,cURL 支持流式写入,而 file_get_contents 会将全部内容加载到内存中,需注意内存限制。