国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

關于file_get_contents返回為空或函數不可用的解決方案

2024-05-04 23:11:22
字體:
來源:轉載
供稿:網友
如果你使用file_get_contents獲取遠程文件內容返回為空或提示該函數不可用,也許本文能幫到你!
使用file_get_contents和fopen必須空間開啟allow_url_fopen。方法:編輯php.ini,設置allow_url_fopen = On,allow_url_fopen關閉時fopen和file_get_contents都不能打開遠程文件。如果你使用的是虛擬主機可以考慮用curl函數來代替。
curl函數的使用示例:

復制代碼 代碼如下:


$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, ‘');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);


利用function_exists函數來判斷php是否支持file_get_contents,否則用curl函數來代替。
PS
1、如果你的主機服務商把curl也關閉了,那你還是換個主機商吧!
2、allow_url_fopen設為off,并不代表你的主機不支持file_get_content函數。只是不能打開遠程文件而已。function_exists(‘file_get_contents')返回的是true。所以網上流傳的《file_get_contents函數不可用的解決方法》還是不能解決問題。
錯誤代碼:

復制代碼 代碼如下:


if (function_exists(‘file_get_contents')) {
$file_contents = @file_get_contents($url);
}else{
$ch = curl_init();
$timeout = 30;
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);
}


應改為:

復制代碼 代碼如下:


if (function_exists(‘file_get_contents')) {//判斷是否支持file_get_contents
$file_contents = @file_get_contents($url);
}
if ($file_contents == ”) {//判斷$file_contents是否為空
$ch = curl_init();
$timeout = 30;
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);
}


最終代碼:

復制代碼 代碼如下:


function file_get_content($url) {
if (function_exists(‘file_get_contents')) {
$file_contents = @file_get_contents($url);
}
if ($file_contents == ”) {
$ch = curl_init();
$timeout = 30;
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;
}


用法:
echo file_get_content(‘');
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 格尔木市| 灵寿县| 彭山县| 淮滨县| 秦皇岛市| 英吉沙县| 高要市| 中超| 桦南县| 三台县| 太谷县| 辽阳县| 裕民县| 小金县| 杨浦区| 静乐县| 祥云县| 喀喇| 乡宁县| 南陵县| 武定县| 杭锦旗| 文成县| 南岸区| 武鸣县| 营山县| 宁明县| 桃源县| 榆林市| 缙云县| 新绛县| 醴陵市| 康平县| 板桥市| 宁陵县| 太白县| 论坛| 论坛| 惠来县| 西贡区| 资中县|