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

网站建设公司不挣钱的原因

女生可以对男朋友心机到什么程度?(苦)

流浪猫鲍勃 A Street Cat Named Bob (2016)

《不可思议》 金莎

瑞克和莫蒂 Rick and Morty (2013-2019)

会声会影 X7旗舰简体珍藏版

PHP中调用curl get 和 curl post 方法的封装

Visual Basic 6.0 奥运优化版(精简版)