php post数据 url编码格式,http - 我应该对POST数据进行URL编码吗?

@DougW清楚地回答了这个问题,但我仍然想在这里添加一些代码来解释道格的观点。 (并纠正上面代码中的错误)

解决方案1:使用内容类型标头对POST数据进行URL编码:application / x-www-form-urlencoded。

注意:你不需要逐个urlencode $ _POST []字段,http_build_query()函数可以很好地完成urlencoding工作。

$fields = array(

'mediaupload'=>$file_field,

'username'=>$_POST["username"],

'password'=>$_POST["password"],

'latitude'=>$_POST["latitude"],

'longitude'=>$_POST["longitude"],

'datetime'=>$_POST["datetime"],

'category'=>$_POST["category"],

'metacategory'=>$_POST["metacategory"],

'caption'=>$_POST["description"]

);

$fields_string = http_build_query($fields);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$url);

curl_setopt($ch, CURLOPT_POST,1);

curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);

解决方案2:直接将数组作为发布数据传递而不进行URL编码,而Content-Type标题将设置为multipart / form-data。

$fields = array(

'mediaupload'=>$file_field,

'username'=>$_POST["username"],

'password'=>$_POST["password"],

'latitude'=>$_POST["latitude"],

'longitude'=>$_POST["longitude"],

'datetime'=>$_POST["datetime"],

'category'=>$_POST["category"],

'metacategory'=>$_POST["metacategory"],

'caption'=>$_POST["description"]

);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$url);

curl_setopt($ch, CURLOPT_POST,1);

curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);

两个代码段都有效,但使用不同的HTTP标头和正文。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值