php 使用 curl 发送 post 数据的问题

作者:airwin 发布时间:January 15, 2010 分类:LNMP

windows平台, nginx + php-fastcgi 模式

PHP Version 5.2.10
cURL Information libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3

测试代码

1
2
3
4
5
6
7
8
9
10
11
$url = 'http://localhost/x.php';
$post_data = array('a'=>'b');
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

这些代码耗时竟然2秒多
同样的操作用socket方式操作则正常,在毫秒级别

调试发现原因在这句

1
2
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//注意这句, 传入的第三个参数是数组

改为:
1
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));

后,执行时间恢复正常.

手册 上的介绍

CURLOPT_POSTFIELDS:
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.

然后我用socket模拟发送multipart/form-data头,但是并无延时现象,看来是php / curl 的问题, 查看php5.2.12的changelog, 并没有类似这个问题的bug.

暂时没有时间去研究源码, 结论就是

CURLOPT_POSTFIELDS 不要为省事传数组, http_build_query 一下!

标签: PHP, curl, CURLOPT_POSTFIELDS

已有 7 条评论 »

  1. 展哥 展哥

    顶啊,楼主说的好啊

  2. 楼下是白痴

  3. sxxx sxxx

    顶楼上的

  4. 丽哥 丽哥

    顶啊,楼上说的好啊!

添加新评论 »