栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用cURL在PHP中发布文件字符串?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用cURL在PHP中发布文件字符串?

应该可以:这是通过浏览器发布的表格(忽略了不相关的字段):

POST http://host.example.com/somewhere HTTP/1.1Content-Type: multipart/form-data; boundary=---------------------------7da16b2e4026cContent-Length: 105732-----------------------------7da16b2e4026cContent-Disposition: form-data; name="NewFile"; filename="test.jpg"Content-Type: image/jpeg(...raw JPEG data here...)-----------------------------7da16b2e4026cContent-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 . "rn";    $data .= 'Content-Disposition: form-data; name="' . $name . '"';    // note: double endline    $data .= "rnrn";}// populate file fieldsforeach ($fileFields as $name => $file) {    $data .= "--" . $delimiter . "rn";    // "filename" attribute is not essential; server-side scripts may use it    $data .= 'Content-Disposition: form-data; name="' . $name . '";' .  ' filename="' . $name . '"' . "rn";    // this is, again, informative only; good practice to include though    $data .= 'Content-Type: ' . $file['type'] . "rn";    // this endline must be here to indicate end of headers    $data .= "rn";    // the file itself (note: there's no encoding of any kind)    $data .= $file['content'] . "rn";}// last delimiter$data .= "--" . $delimiter . "--rn";$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不会破坏它。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465834.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号