php curl之curlopt_postfields参数使用细节

发布时间:2019-11-30编辑:脚本学堂
本文介绍了php编程中curl的curlopt_postfields参数的用法,有需要的朋友参考下。

php编程中,curl一直是一个很有亮点的工具。

在通常情况下,使用 curl 来提交 post 数据时,已经习惯了这样的写法:
curl_setopt( $ch, curlopt_postfields,$post_data);

但是,这种写法有时并不会很好用,可能会得到服务器返回的 500 错误。
但是尝试在使用 socket 方式向服务器提交数据时,会得到非常正确的结果。
例如,在服务器上面存在一个如下的 php 文件:
 

复制代码 代码示例:
<?php print_r($_server);?>

当采用 curl 在不注意细节的前提下向服务器发送一些数据,可能得到下面这样的结果,这不是理想中的结果:
 

复制代码 代码示例:
[content_type] => multipart/form-data; boundary=—————————-f924413ea122

但是如果在采用 http_build_query($post_data) 来替代 $post_data 再向这个 php 脚本提交数据时,就会得到和上面不同的结果,这才是理想中的结果:
 

复制代码 代码示例:
[content_type] => application/x-www-form-urlencoded

从以上例子看出,使用 curl 并且参数为数据时,向服务器提交数据时,http头会发送content_type: application/x-www-form-urlencoded。这个是正常的网页<form>提交表单时,浏览器发送的头部。而 multipart/form-data 知道这是用于上传文件的表单。包括了 boundary 分界符,会多出很多字节。

php手册上这样说:
the full data to post in a http “post” operation. to post a file, prepend a filename with @ and use the full path. this can either be passed as a urlencoded string like ‘para1=val1?2=val2&…' or as an array with the field name as key and field data as value. if value is an array, the content-type header will be set to multipart/form-data.

使用数组提供 post 数据时,curl 组件大概是为了兼容 @filename 这种上传文件的写法,默认把 content_type 设为了 multipart/form-data。
虽然对于大多数服务器并没有影响,但是还是有少部分服务器不兼容。

结论:在没有需要上传文件的情况下,尽量对 post 提交的数据进行 http_build_query 处理,然后再发送出去,能实现更好的兼容性,更小的请求数据包。