php curl那点事儿

curl是最常用功能之一
初始化句柄 $ch = curl_init(); post 传$data 1. 如果$data是字符串,则Content-Type是application/x-www-form-urlencoded。 2、如果$data是k=>v的数组,则Content-Type是multipart/form-data,
1,Coentent-Type仅在取值为application/x-www-data-urlencoded和multipart/form- data两种情况下,PHP才会将http请求数据包中相应的数据填入$_POST
2,PHP不能识别的Content-Type类型的时候,会将http请求包中相应的数据填入变量$HTTP_RAW_POST_DATA
3, 只有Coentent-Type不为multipart/form-data的时候,PHP不会将http请求数据包中的相应数据填入php: //input,其它情况都会。填入的长度由Coentent-Length指定。
4,只有Content-Type为application/x-www-data-urlencoded时,php://input数据才 跟$_POST数据相一致。
5,php://input数据总是跟$HTTP_RAW_POST_DATA相同,但是php://input 比$HTTP_RAW_POST_DATA更凑效,且不需要特殊设置php.ini
6,PHP会将PATH字段的query_path部分,填入全局变量$_GET。通常情况下,GET方法提交的http请求,body为空。
编码设置
$header = array('Content-Type:application/x-www-form-urlencoded;charset=utf8');
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);

post方式
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

返回值
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

超时
curl_setopt($ch, CURLOPT_TIMEOUT, 20);

执行
curl_exec($ch);

是否有异常
if (curl_errno($ch)) 

关闭
curl_close($ch);

一个实例,post数据到某短信端口:

/**
* $sender 发送人
*$reveivers 收信人手机号 数据格式
*$msg 短信内容
*sname 发送人姓名
*/
function send($sender,$receivers,$msg,$sname){
    
  $tos = "";
  foreach ($receivers as $v) {  //将收信人转为以','分割的字符串
    $tos .= $v.",";
  }
 
  $userName = 'hnxxx**';
  $pwd = 'fuckwl***';
  $st = date('mdHis');  
$post_data = array () ;
'] = getKey($userName, $pwd, $st);
 $st;
  $post_data['Content'] = '【前缀】'.$msg;
  $post_data['CharSet'] = 'utf-8';
  $post_data['Mobiles'] = $tos;
  $url = 'http://www.xxx.com:3070/Http_Service/SendSms';
  $o = "" ;
  foreach ( $post_data as $k => $v )
  {
       $o .= "$k=".urlencode($v)."&" ;
  }
  $post_data = substr($o, 0, -1) ;
  


$curl = curl_init(); $header = array('Content-Type:application/x-www-form-urlencoded;charset=utf8'); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); if (curl_errno($curl)) { echo 'Errno'.curl_error($curl); } curl_close($curl); echo $result; echo $post_data; }