在php中file_get_contents函數可直接采集遠程服務器內容,然后保存到一個變量中了,介理一般都會把file_get_contents、fsockopen等一些IO操作的函數禁用掉,因為它們怕被 DDOS.
那么一般情況下,我們改不了服務器的 inc.php,只能自己寫一套IO來代替上面的PHP函數了,代碼如下:
$url = file_get_contents('http://www.companysz.com/');
我們可以用下面的代碼代替:
- //禁用file_get_contents的解決辦法
- $ch = curl_init();
- $timeout = 10; // set to zero for no timeout
- 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是一個利用URL語法規定來傳輸文件和數據的工具,支持很多協議,如HTTP、FTP、TELNET等,它不會被服務器禁用,所以我們可以用來模擬file_get_contents一樣打開一條URL.
利用function_exists函數來判斷php是否支持一個函數可以輕松寫出下面函數
- <?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;
- }
- ?>
新聞熱點
疑難解答