【问题标题】:file_get_contents URL returns nothingfile_get_contents URL 不返回任何内容
【发布时间】:2017-11-13 20:36:10
【问题描述】:

我正在尝试使用 file_get_contents 获取网站内容(JSON 回复)。但它返回空白变量。试图与谷歌的recaptcha api 通信。当我自己输入 URL 时,它返回 JSON 消息很好,但 file_get_contents 什么也不返回。没有代码,因为没有什么复杂的,只是 file_get_contents("https://....") openssl 开启,allow_url_fopen 默认开启。

添加代码:

$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$this->settings->captcha_secret_code."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$response = json_decode($response, true);

$response 返回 1,如果我们注释掉 json_decoding,$response = ""

【问题讨论】:

  • 您需要共享代码。没关系,如果它“没有什么复杂的”。如果不是,你的猜测和我们的一样好。请阅读:How to create a Minimal, Complete, and Verifiable exampleHow do I ask a good question?。另外,您是否检查过服务器错误日志,看看是否有什么可以帮助您?
  • 已添加代码。但这可能无济于事……日志?还没有。
  • 第一步,在变量中创建 URL,转储该变量并检查 URL 是否正确。
  • 是的。我告诉过,如果我将其转储并粘贴到地址栏中,它会返回预期的结果。
  • 请提供var_dump([$response, $http_response_header, error_get_last()]);的输出

标签: php file-get-contents


【解决方案1】:

尝试使用 ssl 信息添加上下文:

<?php
$url = 'your_url.php';    
$opts = array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
);

$context = stream_context_create($opts);

$result = file_get_contents( $url , NULL, $context );
echo $result;

?>

【讨论】:

    【解决方案2】:

    由于某些原因 file_get_contents 不适用于 https URL。相反,您可以使用 cURL:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, "YOUR_URL");
    $response = curl_exec($ch);
    curl_close($ch);
    
    $response = json_decode($response, true);
    

    更复杂,但它有效:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 2016-03-30
      • 2015-12-16
      • 2012-12-13
      • 2018-01-13
      • 2013-10-08
      • 1970-01-01
      相关资源
      最近更新 更多