php - 在 curl 中以数组或字符串形式发送帖子时的区别
问题描述
我对 php 的 libcurl 有疑问。我正在使用这样的字符串发送帖子数据:
$post="var1=val1&var2=val2";
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded','Accept-Encoding: gzip'));
curl_setopt($this->ch,CURLOPT_ENCODING , "gzip");
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
它工作得很好,但我想改用这样的数组:
$post=array();
$post['var1']="val1";
$post['var2']="val2";
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded','Accept-Encoding: gzip'));
curl_setopt($this->ch,CURLOPT_ENCODING , "gzip");
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
但服务器似乎没有收到同样的东西,我有什么遗漏吗?
解决方案
这里的注释说:
注意:将数组传递给 CURLOPT_POSTFIELDS 会将数据编码为 multipart/form-data,而传递 URL 编码的字符串会将数据编码为 application/x-www-form-urlencoded。
这可能是其他站点不以相同方式识别的原因。作为一种解决方法,您可以使用将数组转换为字符串$post = http_build_query($post);
推荐阅读
- excel - 链接列直到 A 列中的新值
- javascript - 如何在 SAPUI5 v.1.38.39 中正确使用 jQuery.sap.log.debug 而不是 console.log?
- python - 从子文件夹中读取所有图像,调整它们的大小并用 Python 中的原始名称保存它们?
- bash - 如何在 Linux 中将路径传递给 xargs 命令
- c# - 如何将现有文件(图像/mp4/pdf)添加到 ziparchive?- .Net 框架 4.6.2
- azure - 将 Bitbucket 存储库部署到 Azure 存储时出现问题
- rust - 在 Optional 中展开结果
- angular - 如何将 SPA 嵌入 ASP.NET Core 库并从路径提供服务
- java - 如何在 Spring MVC 中使用内容类型 ModelAndView
- c# - 如何将多个列表中的元素合并为一个