PHP和HTTPS

jopen 10年前發布 | 31K 次閱讀 PHP HTTPS PHP開發

最近在研究Hacker News API時遇到一個HTTPS問題。因為所有的Hacker News API都是通過加密的HTTPS協議訪問的,跟普通的HTTP協議不同,當使用PHP里的函數file_get_contents()來獲取API里提供的數據時,出現錯誤,使用的代碼是這樣的:

<?php

$data = file_get_contents("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");

......

當運行上面的代碼是遇到下面的錯誤提示:

PHP Warning:  file_get_contents(): Unable to find the wrapper "https" - did you forget to enable it when you configured PHP? 

下面是截圖:

error1.png

為什么會出現這樣的錯誤?

在網上經過一番搜索,發現遇到這樣錯誤的人還不少,問題很直接,是因為在PHP的配置文件里沒有開啟一個參數,在我本機上是/apache/bin/php.ini里的;extension=php_openssl.dll這一項,需要將前面的分號去掉。你可以用下面的腳本來檢查你的PHP環境的配置:

$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_dump($w);

運行上面的這個腳本片段,在我的機器上得到的結果是:

openssl: no
http wrapper: yes
https wrapper: no
wrappers: array(10) {
  [0]=>
  string(3) "php"
  [1]=>
  string(4) "file"
  [2]=>
  string(4) "glob"
  [3]=>
  string(4) "data"
  [4]=>
  string(4) "http"
  [5]=>
  string(3) "ftp"
  [6]=>
  string(3) "zip"
  [7]=>
  string(13) "compress.zlib"
  [8]=>
  string(14) "compress.bzip2"
  [9]=>
  string(4) "phar"
}

替代方案

發現錯誤,改正錯誤,這很簡單,困難的是,發現錯誤后無法改正錯誤。我原本是想將這個腳本方法遠程主機上,但我無法修改遠程主機的PHP配置,結果是,我無法使用這一方案,但我們不能在一棵樹上吊死,這條路走不通,看看有沒有其它路。

另外一個我經常用的PHP里抓取內容的函數是curl,它比file_get_contents()更強大,提供了很多的可選參數。對于訪問HTTPS內容的問題,我們需要使用的CURL配置參數是:

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

你可以從語義上看出,它是忽略/跳過了SSL安全驗證。也許這不是一個很好的做法,但對于普通的場景中,這幾經足夠了。

下面是利用Curl封裝的一個能訪問HTTPS內容的函數:

openssl: no
http wrapper: yes
https wrapper: no
wrappers: array(10) {
  [0]=>
  string(3) "php"
  [1]=>
  string(4) "file"
  [2]=>
  string(4) "glob"
  [3]=>
  string(4) "data"
  [4]=>
  string(4) "http"
  [5]=>
  string(3) "ftp"
  [6]=>
  string(3) "zip"
  [7]=>
  string(13) "compress.zlib"
  [8]=>
  string(14) "compress.bzip2"
  [9]=>
  string(4) "phar"
}

大家可以試一下,如果遇到什么問題,歡迎來信,或在評論里留言。謝謝。

來自:http://www.techug.com/php-https

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!