Home  >  Article  >  Backend Development  >  php curl 上传文件

php curl 上传文件

WBOY
WBOYOriginal
2016-07-25 08:42:11950browse
假设server端上传文件处理脚本upload.php:
  1. print_r($_POST);
  2. print_r($_FILES);
复制代码

1、使用 CURL 默认的方法

  1. //如果php文件是utf8编码,系统是GBK编码,那么就需要转下编码,要不然Php在系统中找不到这个文件
  2. $file = realpath(mb_convert_encoding('测试图片.JPG','GBK','utf8'));
  3. $file = realpath('temp.jpg'); //要上传的文件
  4. $fields['f'] = '@'.$file; // 前面加@符表示上传图片
  5. $ch =curl_init();
  6. curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
  7. curl_setopt($ch,CURLOPT_POST,true);
  8. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  9. curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  10. $content = curl_exec($ch);
  11. echo $content;
复制代码


2、 另类的做法,有时我们需要将动态产生的内容当做文件上传到远程服务器,却又不想在本地服务器中构建临时文件。这样就有了这个另类的写法

  1. $contents =这里是文件内容,也可以是图片二进制,图片需要修改上传文件类型
  2. TEXT;
  3. $varname = 'my';//上传到$_FILES数组中的 key
  4. $name = '3.txt';//文件名
  5. $type = 'text/plain';//文件类型
  6. $key = "$varname\"; filename=\"$name\r\nContent-Type: $type\r\n";
  7. $fields[$key] = $contents;
  8. $ch =curl_init();
  9. curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
  10. curl_setopt($ch,CURLOPT_POST,true);
  11. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  12. curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  13. $content = curl_exec($ch);
  14. echo $content;
复制代码


上传文件, php, curl


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn