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'));

评论

Popular Posts

《小狗钱钱》[德] 博多·舍费尔

《活法》作者:[日]稻盛和夫 pdf下载

一些有意思的网站和贴子

槭树下的家

麦当劳免费Wifi帐号密码及连接设置

Re:从零开始的异世界生活 (2016)

IGN评选的史上TOP100游戏(2018版)

人类的十个有趣心理效应

Tommai mai rub sak tee - Lydia