Home > php教程 > PHP源码 > body text

php curl upload file

大家讲道理
Release: 2016-11-08 14:23:26
Original
1372 people have browsed it

Assume that the server-side upload file processing script upload.php:

<?php
 
print_r($_POST);
print_r($_FILES);
?>
Copy after login

1. Use the CURL default method



//如果php文件是utf8编码,系统是GBK编码,那么就需要转下编码,要不然Php在系统中找不到这个文件 
$file = realpath(mb_convert_encoding(&#39;测试图片.JPG&#39;,&#39;GBK&#39;,&#39;utf8&#39;));
 
$file = realpath(&#39;temp.jpg&#39;); //要上传的文件 
$fields[&#39;f&#39;] = &#39;@&#39;.$file; // 前面加@符表示上传图片
 
$ch =curl_init();
 
 
curl_setopt($ch,CURLOPT_URL,&#39;http://localhost/upload.php&#39;);
 
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
 
 
$content = curl_exec($ch);
 
echo $content;
Copy after login

2. An alternative approach, sometimes we need to treat dynamically generated content as a file Upload to a remote server but don't want to build temporary files in the local server. This way we have this alternative way of writing

$contents =<<< &#39;TEXT&#39;
这里是文件内容,也可以是图片二进制,图片需要修改上传文件类型
TEXT;
 
$varname = &#39;my&#39;;//上传到$_FILES数组中的 key
$name = &#39;3.txt&#39;;//文件名
$type = &#39;text/plain&#39;;//文件类型
 
$key = "$varname\"; filename=\"$name\r\nContent-Type: $type\r\n";
$fields[$key] = $contents;
 
 
 
$ch =curl_init();
 
 
curl_setopt($ch,CURLOPT_URL,&#39;http://localhost/upload.php&#39;);
 
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
 
 
$content = curl_exec($ch);
 
echo $content;
Copy after login

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!