【问题标题】:Browser opens a link successfully, but not curl and file_get_contents浏览器成功打开链接,但没有 curl 和 file_get_contents
【发布时间】:2019-02-03 20:33:20
【问题描述】:

我正在尝试使用 Instagram API。当我在浏览器中打开以下链接时,它完全没问题,您可以单击它并查看 json 响应: https://www.instagram.com/nasa/?__a=1

当我尝试通过file_get_contents() 打开相同的网址时,我遇到了 403 禁止错误。

所以我尝试使用 curl。这是我的代码:

$url = "https://www.instagram.com/nasa/?__a=1";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);


var_dump($result);

问题是$result 是一个空字符串。当我尝试使用 file_get_contents 获取内容时,我遇到 403 Forbidden Error,当我尝试使用 curl 获取内容时,它返回一个空字符串。

Somebody 能帮上忙吗? Tnx。

编辑
我的浏览器没有出现 403 Forbidden,因为我已登录。

【问题讨论】:

  • 当我尝试在浏览器上打开 url 时出现 403 错误,因此必须通过身份验证才能获取内容。您可能没有在浏览器上看到错误,因为您正在登录。
  • @nerea 是的,我检查并登录了。我没有注意到。

标签: php curl file-get-contents


【解决方案1】:

您需要启用 cookie 支持(例如 CURLOPT_COOKIEFILE)并登录才能访问 https://www.instagram.com/nasa/?__a=1 ,并且您的 curl 代码永远不会尝试登录。

在这里您可以看到如何使用 PHP 登录 Instagram:https://stackoverflow.com/a/41684531/1067003

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2019-11-24
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多