Home >php教程 >php手册 >php curl发送post请求的注意点

php curl发送post请求的注意点

WBOY
WBOYOriginal
2016-06-06 19:40:441168browse

先看一段典型的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的代码:
<span>$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);
</span>



这段代码提交出去的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); 这句代码可以放在后面,代码如下:

<span>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
<span>curl_setopt($ch, CURLOPT_POST, 1);
</span>curl_exec($ch);
curl_close($ch);
</span>



 

但$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' (要用绝对路径)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn