【问题标题】:file_get_contents from specific URL来自特定 URL 的 file_get_contents
【发布时间】:2014-01-30 01:42:54
【问题描述】:

我有一个验证请求 URL 的 API 密钥

如果我这样做

echo file_get_contents('http://myfilelocation.com/?apikey=1234');

结果: this api key is not authorized for this domain

但是,如果我将请求的 URL 放在具有相同 URL 的 iframe 中:

结果: this api key is authorized

显然,我正在获取请求的 JSON 返回数据的服务器工作正常,因为 iframe 正在输出正确的信息。但是,如何验证 PHP 是否从正确的域和 URL 设置发出请求?

通过使用file_get_contents,我总是返回 API 密钥未经授权。但是,我正在从授权域运行 php 脚本。

【问题讨论】:

  • file_get_contents 不发送任何关于域的信息。联系 API 开发人员了解他们执行的检查
  • IOW API 开发人员必须检查用户代理之类的东西,看看是否存在,可能是为了防止机器人发出请求。您将需要使用 curl 以便可以设置用户代理等内容。但是您需要联系 API 开发人员以了解他们专门寻找的内容,以便您可以使用 curl 的适当设置

标签: php api curl file-get-contents


【解决方案1】:

试试这个 PHP 代码:

<?php
$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Host: myfilelocation.com\r\n". // Don't forgot replace with your domain
              "Accept-language: en\r\n" .
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n"
  )
);

$context = stream_context_create($options);
$file = file_get_contents("http://myfilelocation.com/?apikey=1234", false, $context);
?>

【讨论】:

  • 你应该解释为什么这行得通,以及为什么 OP 的方法行不通。
【解决方案2】:

file_get_contents 不发送任何推荐人信息,api 可能需要它,这可能会对您有所帮助:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://myfilelocation.com/?apikey=1234');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_REFERER, 'http://autorized-domain.here');
$html = curl_exec($ch);

echo $html;
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2020-05-22
    相关资源
    最近更新 更多