php curl上传文件返回false,PHP: CURLFile::__construct - Manual

There are "@" issue on multipart POST requests.

Solution for PHP 5.5 or later:

- Enable CURLOPT_SAFE_UPLOAD.

- Use CURLFile instead of "@".

Solution for PHP 5.4 or earlier:

- Build up multipart content body by youself.

- Change "Content-Type" header by yourself.

The following snippet will help you :D

* For safe multipart POST request for PHP5.3 ~ PHP 5.4.

*

* @param resource $ch cURL resource

* @param array $assoc "name => value"

* @param array $files "name => path"

* @return bool

*/functioncurl_custom_postfields($ch, array$assoc= array(), array$files= array()) {// invalid characters for "name" and "filename"static$disallow= array("\0","\"","\r","\n");// build normal parametersforeach ($assocas$k=>$v) {$k=str_replace($disallow,"_",$k);$body[] =implode("\r\n", array("Content-Disposition: form-data; name=\"{$k}\"","",filter_var($v),

));

}// build file parametersforeach ($filesas$k=>$v) {

switch (true) {

casefalse===$v=realpath(filter_var($v)):

case !is_file($v):

case !is_readable($v):

continue;// or return false, throw new InvalidArgumentException}$data=file_get_contents($v);$v=call_user_func("end",explode(DIRECTORY_SEPARATOR,$v));$k=str_replace($disallow,"_",$k);$v=str_replace($disallow,"_",$v);$body[] =implode("\r\n", array("Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"","Content-Type: application/octet-stream","",$data,

));

}// generate safe boundarydo {$boundary="---------------------".md5(mt_rand() .microtime());

} while (preg_grep("/{$boundary}/",$body));// add boundary for each parametersarray_walk($body, function (&$part) use ($boundary) {$part="--{$boundary}\r\n{$part}";

});// add final boundary$body[] ="--{$boundary}--";$body[] ="";// set optionsreturn @curl_setopt_array($ch, array(CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>implode("\r\n",$body),CURLOPT_HTTPHEADER=> array("Expect: 100-continue","Content-Type: multipart/form-data; boundary={$boundary}",// change Content-Type),

));

}?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值