在本地测试中,使用file_get_contents获取远程服务器的资源是可以的:
public function send_post($url, $post_data = null) {
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'GET',//POST or GET
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 15 * 60 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
public function getContent(){
$url = "https://www.baidu.com/";
$result = $this->send_post($url);
echo $result;
}
但是,部署在阿里服务器上面时,就没响应了,此时php.ini文件中allow_url_fopen是开启的,也就是说可能是服务商把file_get_contents关闭了;
可以更好为以下函数就可:
/**
* 通用CURL请求
* @param $url 需要请求的url
* @param null $data
* return mixed 返回值 json格式的数据
*/
public function http_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$info = curl_exec($curl);
curl_close($curl);
return $info;
}