您的位置:首页 > 理论基础 > 计算机网络

php使用curl发起http请求

2015-05-07 09:54 169 查看
最近在做基于codeigniter的二次开发,有用到需要跟其他系统进行数据交互,当然最开始想到的,还是使用http请求啦,所以我们需要在php中发起http请求。

环境:win7+wampserver2.4+php5.5

请确认你的php模块中,开启了curl;检查方法在wampserver的php扩展菜单中找到php_curl,并且勾选,或者在php.ini文件夹中,将php_curlzhus

好了,废话不多说,直接上代码:

POST请求

// post方式
$phoneNumber = "13912345678";
$message = "hello world";
$curlPost = "phone=" . urlencode ( $phoneNumber ) . "&message=" . $message;
$ch = curl_init ();
// 访问的url
curl_setopt ( $ch, CURLOPT_URL, 'http://192.168.0.170/stb/testReceive.php' );
// 设置不取回返回的头信息
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
// 设置是通过post还是get方法  1:是post请求 0:是get请求
curl_setopt ( $ch, CURLOPT_POST, 1 );
/*
* 设置请求头信息的地方 $header是头信息的数组,例如:
*
* $header = array (
"POST {$path}?{$query} HTTP/1.1",
"Host: {$temp['host']}",
"Content-Type: text/xml; charset=utf-8",
"Accept: 根据需要填写",
"Referer: http://{$temp['host']}/", 'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1)',
"X-Forwarded-For: {$myIp}",
"Content-length: 380",
"Connection: Close"
);
*/
// 		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// CURLOPT_TIMEOUT 设置cURL允许执行的最长秒数。只需要设置一个秒的数量就可以
curl_setopt($ch, CURLOPT_TIMEOUT,60);
// 传递post体信息
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $curlPost );
// 发起请求,返回结果
$data = curl_exec ( $ch );
// 错误好
$curl_errno = curl_errno($ch);
// 错误信息
$curl_error = curl_error($ch);
curl_close ( $ch );

if($curl_errno >0){
echo "cURL Error ($curl_errno): $curl_error\n";
}else{
echo "Data received: $data\n";
}


GET请求

//get方式
$phoneNumber ="18666668888";
$message = "send message";
$curlPost = "phone=".urlencode($phoneNumber)."&message=".$message;
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,'http://192.168.0.170/stb/testReceive.php'.'?'.$curlPost);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,0);
//设置是通过post还是get方法
curl_setopt($ch,CURLOPT_POST,0);
//传递的变量
// 		curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost);
$data = curl_exec($ch);
var_dump($data);
curl_close($ch);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: