curl提供了两种Post提交模式:
1。对Post内容进行url编码处理,将编码后的字符串传递给curl
$post = array('k1'=>'v1','k2'=>'v2');
$tmp = array();
foreach($post as $k=>$v){
$tmp[] = urlencode($k)."=".urlencode($v);
}
$params = implode("&",$tmp);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_URL,$_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$content = curl_exec ($ch);
curl_close ($ch);
向服务器发送的内容实际如下:
POST /mail/u.php HTTP/1.1
Host: xxxxxxxx
Accept: */*
Content-Length: 11
Content-Type: application/x-www-form-urlencoded
k1=v1&k2=v2
2。直接给一个数组参数,由CURL自行处理;这种情况下,Curl会将post内容使用multipart的方式发送到服务器。
$post = array('k1'=>'v1','k2'=>'v2');
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post );
curl_setopt($ch, CURLOPT_URL,$_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$content = curl_exec ($ch);
curl_close ($ch);
向服务器发送的实际内容如下:
POST /mail/u.php HTTP/1.1
Host: xxxxxxxx
Accept: */*
Content-Length: xxxxxxx
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------aeb80cb56454
Content-Disposition: form-data; name="k1"
v1
-----------------------------aeb80cb56454
Content-Disposition: form-data; name="k2"
v2
-----------------------------aeb80cb56454
curl自己提供了文件处理功能,只需要在对上面的$post中key-value对做小小的改变:
$post = array('k1'=>'@/tmp/a.txt','k2'=>'v2');
这样,就相当于在form表单中增加了一个name=k1的file控件,选中的文件绝对路径为/tmp/a.txt,前面带@符号表明这是一个文件,curl对获取文件的内容,并将文件名等信息发送到服务器。
Content-Disposition: form-data; name="k1"; filename="a.txt"
Content-Type: text/plain
this is file a.txt 's content
-----------------------------aeb80cb56454
但是,这需要在服务器上存在文件/tmp/a.txt,而当我们只有文件内容而没有文件存在,在服务器上也没有写权限时,就没有办法通过这种办法发送文件了;这时候,我们只能自己构造multipart请求,然后使用curl发送出去。
$ch = curl_init($url);
$rand = rand("100000000",'900000000');
$header[] ="Content-Type: multipart/form-data; boundary=---------------------------$rand";
$image = "this is image's content";
$mime = '-----------------------------'.$rand.'
Content-Disposition: form-data; name="k1"; filename="ff.jpg"
Content-Type: image/jpeg
'.$image.'
-----------------------------'.$rand.'
Content-Disposition: form-data; name="k2"
v2
-----------------------------'.$rand.'--
';
$header[] ="Content-Length: ".strlen($mime);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $mime);
$response = curl_exec($ch);
$response_info=curl_getinfo($ch);
curl_close($ch);