赶知识网

PHP使用CURL上传文件的函数

2010-04-09 / 6963次点击 php/mysql/apache

一般的文件上传是通过html表单进行的,通过CURL可以不经过浏览器,直接在服务器端模拟进行表单提交,完成POST数据、文件上传等功能。需要被上传的文件需要在文件名前加上“@”以示区分,并且,文件名需要是完整路径。

以下php函数来模拟html表单的提交数据:

function uploadByCURL($post_data,$post_url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $post_url);
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_USERAGENT,"Mozilla/4.0");
$result = curl_exec($curl);
$error = curl_error($curl);
return $error ? $error : $result;
}

函数的使用:

$url = "http://127.0.0.1/app.php";
$data = array(
"username" => $username,
"password"  => $password,
"file1"  => "@".realpath("photo1.jpg"),
"file2"  => "@".realpath("file2.xml")
);
print_r(uploadByCURL($data,$url));
 
用curl下载网页估计大家都会,但是模拟 multipart/form-data 形式的 form 上传文件则稍稍复杂些。命令行如下。

curl -F "action=upload" -F "filename=@file.tar.gz" http://localhost/action.php

  如果使用了-F参数,curl就会以 multipart/form-data 的方式发送POST请求。-F参数以name=value的方式来指定参数内容,如果值是一个文件,则需要以name=@file的方式来指定。

  如果通过代理,上面的命令有可能会被代理拒绝,这时需要指定上传文件的MIME类型。

curl -x myproxy.com:1080 -F "action=upload" -F "filename=@file.tar.gz;type=application/octet-stream" http://localhost/action.php

  另外,如果不上传文件,则可以使用 -d 参数,这时curl会以 application/x-www-url-encoded 方式发送 POST 请求。

curl -d "action=del" -d "id=12" http://localhost/action.php

 

用curl上传文件的话很方便,什么header,post串都不用生成了,用fsockopen要写一堆
curl:
==============

PHP code
$file = array("upimg"=>"@E:/png.png");//文件路径,前面要加@,表明是文件上传.
$curl = curl_init("http://localhost/a.php");
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$file);
curl_exec($curl);


fsockopen:
===============

PHP code
$uploadFile = file_get_contents("E:/png.png");
$boundary   = md5(time());

$postStr .="--".$boundary."\r\n";//边界开始,注意默认比header定义的boundary多两个'-'
$postStr .="Content-Disposition: form-data; name=\"upimg\"; filename=\"E:/png.png\"\r\n";
$postStr .="Content-Type: image/png\r\n\r\n";
$postStr .=$uploadFile."\r\n";
$postStr .="--".$boundary."\r\n";//边界结束
fwrite($fp,"POST /a.php HTTP/1.0\r\n");
fwrite($fp,"Content-Type: multipart/form-data; boundary=".$boundary."\r\n");
fwrite($fp,"Content-length:".strlen($postStr)."\r\n\r\n");
fwrite($fp,$postStr);
while (!feof($fp)){
     echo fgets($fp, 128);
}
fclose($fp);


a.php
==============

PHP code
print_r($_FILES);

 

有用 0 没用 1

Top10

沪ICP备09053415号 © 赶知识网