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

浩方对战平台优化版 V2.05 部分去除浩方广告和弹出窗口

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

Debian 12上使用Nginx代理TCP流量,并配置IPv6白名单访问控制

中兴ZTE H618B 路由器固件刷机备忘

MIFARE Classic Tool - 安卓NFC门禁卡修改工具

Microsoft 365安装包下载(Office桌面应用)

解决word和excel运行时错误:91未设置对象变量或with block变量

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

U盾安装及检测不到U盾问题的排查方法