php curl post 字符串,使用PHP中的cURL POST文件字符串?

应该是可能的:这里是一个窗体,通过浏览器发布(不相关的字段省略):

POST http://host.example.com/somewhere HTTP/1.1

Content-Type: multipart/form-data; boundary=---------------------------7da16b2e4026c

Content-Length: 105732

-----------------------------7da16b2e4026c

Content-Disposition: form-data; name="NewFile"; filename="test.jpg"

Content-Type: image/jpeg

(...raw JPEG data here...)

-----------------------------7da16b2e4026c

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

content of otherformfield is this text

-----------------------------7da16b2e4026c--

所以,如果我们自己构建POST主体并设置一个额外的标题或两个,我们应该能够模拟这:

// form field separator

$delimiter = '-------------' . uniqid();

// file upload fields: name => array(type=>'mime/type',content=>'raw data')

$fileFields = array(

'file1' => array(

'type' => 'text/plain',

'content' => '...your raw file content goes here...'

), /* ... */

);

// all other fields (not file upload): name => value

$postFields = array(

'otherformfield' => 'content of otherformfield is this text',

/* ... */

);

$data = '';

// populate normal fields first (simpler)

foreach ($postFields as $name => $content) {

$data .= "--" . $delimiter . "\r\n";

$data .= 'Content-Disposition: form-data; name="' . $name . '"';

// note: double endline

$data .= "\r\n\r\n";

}

// populate file fields

foreach ($fileFields as $name => $file) {

$data .= "--" . $delimiter . "\r\n";

// "filename" attribute is not essential; server-side scripts may use it

$data .= 'Content-Disposition: form-data; name="' . $name . '";' .

' filename="' . $name . '"' . "\r\n";

// this is, again, informative only; good practice to include though

$data .= 'Content-Type: ' . $file['type'] . "\r\n";

// this endline must be here to indicate end of headers

$data .= "\r\n";

// the file itself (note: there's no encoding of any kind)

$data .= $file['content'] . "\r\n";

}

// last delimiter

$data .= "--" . $delimiter . "--\r\n";

$handle = curl_init($url);

curl_setopt($handle, CURLOPT_POST, true);

curl_setopt($handle, CURLOPT_HTTPHEADER , array(

'Content-Type: multipart/form-data; boundary=' . $delimiter,

'Content-Length: ' . strlen($data)));

curl_setopt($handle, CURLOPT_POSTFIELDS, $data);

curl_exec($handle);

这样,我们正在做所有的重担,并相信cURL不要弄错它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值