常规方法post请求:
function sendPost($url, $post_data) {
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 5 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
curl方法post请求:
function sendPost($url,$data=array()){
$ch = curl_init();
//设置选项,包括URL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_TIMEOUT,5); //定义超时5秒钟
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); //所需传的数组用http_bulid_query()函数处理一下
$result = curl_exec($ch);
$errorCode = curl_errno($ch);
//释放curl句柄
curl_close($ch);
if(0 !== $errorCode) { return false; }
return $result;
}
调用示例:
$url='http://www.hilo8.com/xxx';
$data=array('act'=>'abc','id'=>168);
$res = sendPost($url, $data);
echo $res;
上一篇:PHP字符串转数组或数组转字符串
讨论数量:0