關於file_get_contents返回False的問題


在本地測試中,使用file_get_contents獲取遠程服務器的資源是可以的:

 1     public function send_post($url, $post_data = null) {
 2         $postdata = http_build_query($post_data);
 3         $options = array(
 4             'http' => array(
 5                 'method' => 'GET',//POST or GET
 6                 'header' => 'Content-type:application/x-www-form-urlencoded',
 7                 'content' => $postdata,
 8                 'timeout' => 15 * 60 // 超時時間(單位:s)
 9             )
10         );
11         $context = stream_context_create($options);
12         $result = file_get_contents($url, false, $context);
13         return $result;
14     }
1     public function getContent(){
2         $url = "https://www.baidu.com/";
3         $result = $this->send_post($url);
4         echo $result;
5     }

但是,部署在阿里服務器上面時,就沒響應了,此時php.ini文件中allow_url_fopen是開啟的,也就是說可能是服務商把file_get_contents關閉了;

可以更好為以下函數就可:

 1 /**
 2      * 通用CURL請求
 3      * @param $url  需要請求的url
 4      * @param null $data
 5      * return mixed 返回值 json格式的數據
 6      */
 7     public function http_request($url, $data = null)
 8     {
 9         $curl = curl_init();
10         curl_setopt($curl, CURLOPT_URL, $url);
11         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
12         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
13         if (!empty($data)) {
14             curl_setopt($curl, CURLOPT_POST, 1);
15             curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
16         }
17         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
18         $info = curl_exec($curl);
19         curl_close($curl);
20         return $info;
21     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM