A-A+

解决file_get_contents无法请求https连接的方法

2020年08月08日 我爱编程 暂无评论

PHP.ini默认配置下,用file_get_contents读取https的链接,就会报如下错误,本文给出解决方法

错误: Warning: fopen() [function.fopen]: Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

解决方案有3:

1.windows下的PHP,只需要到php.ini中把extension=php_openssl.dll前面的;删掉,重启服务就可以了。

2.linux下的PHP,就必须安装openssl模块,安装好了以后就可以访问了。

3.如果服务器你不能修改配置的话,那么就使用curl函数来替代file_get_contents函数,当然不是简单的替换啊。还有相应的参数配置才能正常使用curl函数。

对curl函数封装如下:

  1. function http_request($url,$timeout=30,$header=array()){
  2.         if (!function_exists('curl_init')) {
  3.             throw new Exception('server not install curl');
  4.         }
  5.         $ch = curl_init();
  6.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  7.         curl_setopt($ch, CURLOPT_HEADER, true);
  8.         curl_setopt($ch, CURLOPT_URL, $url);
  9.         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  10.         if (!emptyempty($header)) {
  11.             curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  12.         }
  13.         $data = curl_exec($ch);
  14.         list($header$data) = explode("\r\n\r\n"$data);
  15.         $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  16.         if ($http_code == 301 || $http_code == 302) {
  17.             $matches = array();
  18.             preg_match('/Location:(.*?)\n/'$header$matches);
  19.             $url = trim(array_pop($matches));
  20.             curl_setopt($ch, CURLOPT_URL, $url);
  21.             curl_setopt($ch, CURLOPT_HEADER, false);
  22.             $data = curl_exec($ch);
  23.         }
  24.         if ($data == false) {
  25.             curl_close($ch);
  26.         }
  27.         @curl_close($ch);
  28.         return $data;
  29. }

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录