php curl发送post请求的注意点

先看一段典型的CURL POST的代码:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
curl_close($ch);



这段代码提交出去的Content-Type到底是multipart/form-data还是application/x-www-form-urlencoded呢?事实证明Content-Type的类型取决于$data的数据类型。

如果
$data
是字符串,如:$data ='file=content&name=lifreshman';则Content-Type是application/x-www-form-urlencoded。

如果
$data
是k=>v的数组,如:

$post_data = array(  
  'file' => 'asdfasdf',  
  'endpoint' => ‘test’,
  'timestamp'=> $timeStamp,
  'authKey' => $authkey
);则Content-Type是multipart/form-data

还有一个非常重要的问题,这个小问题花费了我几天时间:

$data是字符串时,curl_setopt($ch, CURLOPT_POST, 1); 这句代码可以放在后面,代码如下:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_exec($ch);
curl_close($ch);



 

但$data是k=>v的数组时,curl_setopt($ch, CURLOPT_POST, 1); 必须在设置发送数据curl_setopt($ch, CURLOPT_POSTFIELDS, $data);的前面,否则发送不成功,我当时就是因为放在了后面导致post数组时一直不成功:

 

curl的手册:http://php.net/manual/en/function.curl-setopt.php  (还是很有用的)

其中一句话:“If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.“解决了我的问题

 

补充一点,如果想发送文件内容,可以设置如下参数 'file'=>'@/usr/local/apache/htdocs/airportCitys.txt' (要用绝对路径)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值