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

PHP调用Instagram GraphQL接口遭遇HTTP 403 Forbidden错误求助

解决Instagram GraphQL接口PHP请求403 Forbidden问题

你遇到的403 Forbidden错误,本质是Instagram的反爬机制识别出你的请求来自PHP脚本而非真实浏览器,下面是几个可行的解决办法:


1. 给file_get_contents添加浏览器请求头

默认情况下,file_get_contents发送的请求会带上类似PHP/7.x.x的User-Agent,很容易被识别为非浏览器请求。我们可以通过stream_context_create模拟浏览器的请求头:

$insta_id = $ret->users[0]->user->pk;
$link1 = "https://www.instagram.com/graphql/query/?query_hash=42323d64886122307be10013ad2dcc44&variables=%7B%22id%22:%22".$insta_id."%22,%22first%22:12,%22after%22:%22AQDea0aZ27W349lmEWRcuh9xz7sO2Elo-_RDymqEMzT85he8dFwkrV4lbKlii9z7AkWPEbLx_txFKKbHeuotw9c4fY40B-Mm-lF7sfWtq8PUfQ%22%7D";

// 模拟Chrome浏览器的请求头
$context = stream_context_create([
    'http' => [
        'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36\r\n"
    ]
]);

$response1 = file_get_contents($link1, false, $context);

这个方法只需要添加User-Agent就能解决大部分公开接口的403问题。


2. 使用cURL替代file_get_contents(推荐)

cURL比file_get_contents更灵活,支持更多请求配置,也更便于排查错误:

$insta_id = $ret->users[0]->user->pk;
$link1 = "https://www.instagram.com/graphql/query/?query_hash=42323d64886122307be10013ad2dcc44&variables=%7B%22id%22:%22".$insta_id."%22,%22first%22:12,%22after%22:%22AQDea0aZ27W349lmEWRcuh9xz7sO2Elo-_RDymqEMzT85he8dFwkrV4lbKlii9z7AkWPEbLx_txFKKbHeuotw9c4fY40B-Mm-lF7sfWtq8PUfQ%22%7D";

$ch = curl_init();
// 设置请求URL
curl_setopt($ch, CURLOPT_URL, $link1);
// 让cURL返回结果而不是直接输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 模拟浏览器User-Agent
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36");
// 可选:处理HTTPS证书问题(生产环境建议配置合法CA证书)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$response1 = curl_exec($ch);

// 检查请求是否失败
if ($response1 === false) {
    echo "请求错误:" . curl_error($ch);
} else {
    // 解析返回的JSON数据
    $data = json_decode($response1, true);
    var_dump($data);
}

curl_close($ch);

3. 额外注意事项

  • 接口稳定性:Instagram的GraphQL接口属于未公开的内部接口,query_hash随时可能失效,需要定期验证更新。
  • 登录权限:如果要访问私有账号内容,需要在请求头中添加登录后的sessionid等Cookie字段(可以从浏览器开发者工具中复制)。
  • 防封禁:避免高频请求,建议添加请求间隔,必要时使用代理IP分散请求来源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:05:00