先看一段典型的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到底是multipa
先看一段典型的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' (要用绝对路径)