以下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:
===============
$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);
<?php
$ch = curl_init();
$data = array(
'aid' => '1665',
'uname'=>'mickelfeng',
'pwd'=>'123456',
'mode'=>'1',
'title'=>"mickelfeng",
'audio'=>"@".realpath("da.mp3"),
'desc'=>'mickelfeng'
);
// 设置URL和相应的选项
curl_setopt($ch, CURLOPT_URL, "http://xxx/PostTest.php");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// 抓取URL并把它传递给浏览器
$c=curl_exec($ch);
// 关闭cURL资源,并且释放系统资源
curl_close($ch);
?>