众所周知,用curl上传只要设置4个变量即可(非HTTPS网站),那就是curlopt_url,curlopt_post,curlopt_returntransfer,curlopt_postfields,当然这4个都是大写。
curlopt_post,curlopt_returntransfer 都是 true,curlopt_url则是你要提交的网址,那么剩下的,curlopt_postfields就是你要上传的内容了。
上传文件在这里也变得非常简单,只需对应的值前面加个“@”即可,如curl_setopt($ch,CURLOPT_POSTFIELDS,array('file'=>'@/var/www/images/abc.jpg')); 文件通过realpath判断后存在的即可。
但是,这一切在php5.6里就发生了改成。php5.6不再支持@这样的上传方式,只能使用curl_file_create的方式来,所以上面的代码要改成
PHP代码
- curl_setopt($ch,CURLOPT_POSTFIELDS,array('file'=>curl_file_create('/var/www/images/abc.jpg','image/jpg','abc')));
看看文档里怎么说:
XML/HTML代码
- CURLFile should be used to upload a file with CURLOPT_POSTFIELDS.
然后官网的手册中的最后一条评论,仿佛是看不下去,写了个处理上传的程序
PHP代码
- 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
- <?php
- /**
- * 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
- */
- function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {
- // invalid characters for "name" and "filename"
- static $disallow = array("\0", "\"", "\r", "\n");
- // build normal parameters
- foreach ($assoc as $k => $v) {
- $k = str_replace($disallow, "_", $k);
- $body[] = implode("\r\n", array(
- "Content-Disposition: form-data; name=\"{$k}\"",
- "",
- filter_var($v),
- ));
- }
- // build file parameters
- foreach ($files as $k => $v) {
- switch (true) {
- case false === $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 boundary
- do {
- $boundary = "---------------------" . md5(mt_rand() . microtime());
- } while (preg_grep("/{$boundary}/", $body));
- // add boundary for each parameters
- array_walk($body, function (&$part) use ($boundary) {
- $part = "--{$boundary}\r\n{$part}";
- });
- // add final boundary
- $body[] = "--{$boundary}--";
- $body[] = "";
- // set options
- return @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
- ),
- ));
- }
好吧,其实多文件上传用这样的方式就挺好。