PHP使用file_get_contents发送HTTP GET和POST请求
$url传入请求网址,$data传入参数数组,如果$data为空,表示GET请求,反之则是POST请求
function httpRequest($url, $data = null, $user = null, $pass = null)
{
//$url = 'https://ktsee.com/api';
//$data = array('key1' => 'value1', 'key2' => 'value2');
if (isset($data) && is_array($data)) {
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencodedrn",
'method' => 'POST',
'content' => http_build_query($data)
)
);
if (isset($user) && !empty($user) && isset($user) && !empty($pass)) {
$auth = sprintf('Authorization: Basic %s', base64_encode($user . ':' . $pass));
$options['http']['header'] .= $auth . "rn";
}
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
} else {
$result = file_get_contents($url);
}
if ($result === FALSE) {
/* Handle error */
return null;
} else {
return $result;
}
}
调用方法:httpRequest('https://ktsee.com/api');
httpRequest('https://ktsee.com/api',array('name'=>'a','nickname'=>'b'));
评论