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扫描版

CuteHttpFileServer/chfs 文件服务器,支持http,webdav,多平台

5个免费的在线笔记本服务

New Balance 各型号特点

长方形带把手Tritan随手杯