php中的curl几点需要注意的地方

1 CURLOPT_POSTFIELDS中的玄机

curl_setop($ch, CURLOPT_POSTFIELDS, $var); 但不知道内有玄机,php的doc里面有这么一段话。

If value is an array, the Content-Type header will be set to multipart/form-data.

要知道一般POST时,会以application/x-www-form-urlencoded 的 Content-Type POST。而 multipart/form-data 一般用于上传文件。

关于两者的区别,不想读rfc的可以先看看 http://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data

两种情形下POST样例:

application/x-www-form-urlencoded 形式的POST

POST / HTTP/1.1
Host: 192.168.201.197
Accept: */*
Accept-Encoding: gzip
Content-Length: 8
Content-Type: application/x-www-form-urlencoded

url=xxxx

multipart/form-data 格式的POST:

POST / HTTP/1.1
Host: 192.168.201.197
Accept: */*
Accept-Encoding: gzip
Content-Length: 153
Content-Type: multipart/form-data; boundary=----------------------------e62c3de4a033

Content-Disposition: form-data; name="url"

xxx

2 curl中PUT文件

现在都流行RESTful的接口,很多接口要求客户端PUT方式上传文件。在php中,使用curl发起PUT的请求,有两种方法:

curl_setopt($ch, CURLOPT_PUT, 1);
或者
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');

当你想使用PUT上传文件时,请不要使用第二种,因为它不会上传文件。

 

- to blog -

blog built using the cayman-theme by Jason Long. LICENSE