PHP和HTTPS

來源:互聯網
上載者:User
最近在研究Hacker News API時遇到一個HTTPS問題。因為所有的Hacker News API都是通過加密的HTTPS

協議訪問的,跟普通的HTTP協議不同,當使用PHP裡的函數file_get_contents()來擷取API裡提供的數

據時,出現錯誤,使用的代碼是這樣的:

$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?

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

在網上經過一番搜尋,發現遇到這樣錯誤的人還不少,問題很直接,是因為在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內容的函數:

function getHTTPS($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;

}

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.