如何使file_get_contents()与HTTPS一起使用?

问题描述 投票:99回答:12

我正在设置信用卡处理程序,需要对CURL使用替代方法。当我使用测试服务器(未调用SSL URL)时,以下代码可以正常工作,但是现在当我在使用HTTPS的工作服务器上对其进行测试时,它失败,并显示错误消息“无法打开流”。

function send($packet, $url) {
  $ctx = stream_context_create(
    array(
      'http'=>array(
        'header'=>"Content-type: application/x-www-form-urlencoded",
        'method'=>'POST',
        'content'=>$packet
      )
    )
  );
  return file_get_contents($url, 0, $ctx);
}
php curl https file-get-contents
12个回答
87
投票

尝试以下脚本,查看是否有适用于您的PHP脚本的https包装器。

$w = stream_get_wrappers();
echo 'openssl: ',  extension_loaded  ('openssl') ? 'yes':'no', "\n";
echo 'http wrapper: ', in_array('http', $w) ? 'yes':'no', "\n";
echo 'https wrapper: ', in_array('https', $w) ? 'yes':'no', "\n";
echo 'wrappers: ', var_export($w);

输出应该类似于

openssl: yes
http wrapper: yes
https wrapper: yes
wrappers: array(11) {
  [...]
}

1
投票

有时,服务器将根据它在http请求标头(例如适当的用户代理)中看到或未看到的内容选择不响应。如果可以连接浏览器,请抓住它发送的标题并在您的流上下文中模拟它们。


0
投票

我在IIS上无法正常使用https。解决:


-1
投票

检查URL是否正常


113
投票

允许使用https包装器:

  • php_openssl扩展名必须存在并启用
  • [allow_url_fopen必须设置为on

在php.ini文件中,如果不存在,则应添加以下行:

extension=php_openssl.dll

allow_url_fopen = On

51
投票

尝试以下操作。

function getSslPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

注意:这将禁用SSL验证,这意味着提供的安全性通过HTTPS丢失]]。仅将此代码用于测试/本地开发,从不上网或其他面向公众的网络。如果此代码有效,则表示SSL证书不是受信任或无法验证,您应该将其视为单独的问题。


37
投票
$url= 'https://example.com';

$arrContextOptions=array(
      "ssl"=>array(
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ),
    );  

$response = file_get_contents($url, false, stream_context_create($arrContextOptions));

9
投票

这可能是由于您的目标服务器没有有效的SSL证书。


6
投票

只需在您的php.ini文件中添加两行。


5
投票

我有同样的错误。将allow_url_include = On中的php.ini设置为我固定。


5
投票

HTTPS从PHP 4.3.0开始受支持,如果已编译为支持OpenSSL。另外,请确保目标服务器具有有效的证书,防火墙允许出站连接,并且php.ini中的allow_url_fopen设置为true。


3
投票

就我而言,问题是由于WAMP为CLI使用的php.ini与Apache不同,所以您通过WAMP菜单进行的设置不适用于CLI。只需修改CLI php.ini,它就可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.