在本地測試中,使用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 }