订阅本站我的微博客

03/ [译]基于PHP的cURL快速入门(三)

+0
文件上传

上传文件和前面的POST十分相似。因为所有的文件上传表单都是通过POST方法提交的。

首先新建一个接收文件的页面,命名为 upload_output.php:
print_r($_FILES);

以下是真正执行文件上传任务的脚本:
<?php
$url = "http://localhost/upload_output.php";
$post_data = array (
   "foo" => "bar",
   // 要上传的本地文件地址
   "upload" => "@C:/wamp/www/test.zip"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>

03/ PHP使用CURL上传文件的函数

+0
一般的文件上传是通过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));


本文来自:http://flashphp.org