Loading

关于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     }

 

posted @ 2017-02-07 13:55  集君  阅读(9995)  评论(0编辑  收藏  举报