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

eXtplorer - 一个基于PHP和JavaScript的在线文件管理器

随身WiFi折腾指南: 解锁、刷机与DIY

mihomo各平台客户端下载(windows, android, macos)

常用的国内外延迟测速链接(generate_204)

Win10和Win11家庭版开启远程桌面功能RDP

坚持跑步到底有哪些改变?

十二国记 (2002)

优化PC端B站(Bilibili)免登录观看体验

Cromite - 极度注重隐私的Chromium浏览器