You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何读取需要身份验证的远程服务器文件内容?

解决方案

你遇到的问题是因为目标资源开启了HTTP Basic身份验证,默认的file_get_contents请求不会携带身份凭证,所以被服务器拒绝访问,有两种常用实现方案:

方案1:基于原生file_get_contents实现(无需额外扩展)

提前构造包含身份验证信息的流上下文,传入file_get_contents的第三个参数即可,无需修改原有后续解析逻辑:

// 替换为你的实际身份信息与资源地址
$username = '实际用户名';
$password = '实际密码';
$remoteXmlUrl = 'https://dummyurl/feed.xml';

// 构造基础身份验证请求头
$authHeader = 'Authorization: Basic ' . base64_encode($username . ':' . $password);

// 生成请求流上下文
$context = stream_context_create([
    'http' => [
        'header' => $authHeader,
        'method' => 'GET',
        // 若目标为自签SSL证书,可临时开启下方两项跳过校验,生产环境不建议保留
        // 'verify_peer' => false,
        // 'verify_peer_name' => false,
    ]
]);

// 读取远程XML内容
$xml = file_get_contents($remoteXmlUrl, false, $context);
$xml = simplexml_load_string($xml);
$xml_array = json_decode(json_encode((array) $xml), 1);

方案2:基于cURL扩展实现(兼容性更强)

如果你的PHP环境已安装cURL扩展,也可以用cURL实现,对各类异常场景、请求参数的控制灵活度更高:

// 替换为你的实际身份信息与资源地址
$username = '实际用户名';
$password = '实际密码';
$remoteXmlUrl = 'https://dummyurl/feed.xml';

$ch = curl_init($remoteXmlUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 配置基础身份验证
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
// 若目标为自签SSL证书,可临时开启下方两项跳过校验,生产环境不建议保留
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$xml = curl_exec($ch);
curl_close($ch);

// 后续解析逻辑保持不变
$xml = simplexml_load_string($xml);
$xml_array = json_decode(json_encode((array) $xml), 1);

注:以上方案仅适用于最常见的HTTP Basic身份验证场景,若目标站点使用Digest Auth、Bearer Token等其他验证方式,需要对应调整请求头配置。

内容的提问来源于stack exchange,提问作者amit sutar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:15:08