file_get_contents被屏蔽解決方法
來(lái)源:程序員人生 發(fā)布時(shí)間:2013-12-14 03:23:35 閱讀次數(shù):2797次
在php中file_get_contents函數(shù)可直接采集遠(yuǎn)程服務(wù)器內(nèi)容,然后保存到一個(gè)變量中了,介理一般都會(huì)把file_get_contents、fsockopen等一些IO操作的函數(shù)禁用掉,因?yàn)樗鼈兣卤?DDOS.
那么一般情況下,我們改不了服務(wù)器的 inc.php,只能自己寫(xiě)一套IO來(lái)代替上面的PHP函數(shù)了,代碼如下:
$url = file_get_contents('http://www.phpfensi.com/');
我們可以用下面的代碼代替:
-
- $ch = curl_init();
- $timeout = 10;
- curl_setopt ($ch, CURLOPT_URL,'http://www.hzhuti.com/');
- curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
- $url = curl_exec($ch);
curl是一個(gè)利用URL語(yǔ)法規(guī)定來(lái)傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、TELNET等,它不會(huì)被服務(wù)器禁用,所以我們可以用來(lái)模擬file_get_contents一樣打開(kāi)一條URL.
利用function_exists函數(shù)來(lái)判斷php是否支持一個(gè)函數(shù)可以輕松寫(xiě)出下面函數(shù)
- <?php
- function vita_get_url_content($url) {
- if(function_exists('file_get_contents')) {
- $file_contents = file_get_contents($url);
- } else {
- $ch = curl_init();
- $timeout = 5;
- curl_setopt ($ch, CURLOPT_URL, $url);
- curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
- $file_contents = curl_exec($ch);
- curl_close($ch);
- }
- return $file_contents;
- }
- ?>
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)