file_get_contents 请求 HTTPS 报错原因与解决
错误提示:Warning: fopen() [function.fopen]: Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?
针对此问题,主要有以下三种解决方案:
1. 对于 Windows 环境下的 PHP,只需打开 php.ini 配置文件,找到 extension=php_openssl.dll 这一行,删除其前面的分号(;)以启用扩展,随后重启 Web 服务即可生效。
2. 对于 Linux 环境下的 PHP,必须确保系统已安装 openssl 模块。完成安装后,即可正常通过 file_get_contents 访问 HTTPS 资源。
3. 如果受限于服务器权限无法修改配置,则建议使用 curl 函数替代 file_get_contents。需要注意的是,这并非简单的函数名替换,还需进行相应的参数配置才能确保 curl 正常工作。
以下是对 curl 函数的封装实现:
复制代码 代码如下: function http_request($url,$timeout=30,$header=array()){ if (!function_exists('curl_init')) { throw new Exception('server not install curl'); } $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if (!emptyempty($header)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } $data = curl_exec($ch); list($header, $data) = explode("\r\n\r\n", $data); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($http_code == 301 || $http_code == 302) { $matches = array(); preg_match('/Location:(.*?)\n/', $header, $matches); $url = trim(array_pop($matches)); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false); $data = curl_exec($ch); } if ($data == false) { curl_close($ch); } @curl_close($ch); return $data; }