php把文件上传到远程服务器上例子

在这里我们利用curl实现把本地服务器的文件通过curl发送请求给远程服务器的php文件接受就实现了上传,还一个是利用ftp来上传方法也是php中的curl操作ftp服务器进行上传.

我这里写的是用curl的代码,本地代码如下:

  1. <?php
  2. header('content-type:text/html;charset=utf8');
  3. $curl = curl_init();
  4. $data = array('img'=>'@'. dirname(__FILE__).'/img/login.gif');
  5. curl_setopt($curl, CURLOPT_URL, "http://www.demo.com/uploadimg.php");
  6. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  7. curl_setopt($curl, CURLOPT_POST, true);
  8. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  9. $result = curl_exec($curl);
  10. curl_close($curl);
  11. echo json_decode($result);
  12. ?>

远程服务器接受端代码,代码如下:

  1. <?php
  2. if($_FILES)
  3. {
  4. $filename = $_FILES['img']['name'];
  5. $tmpname = $_FILES['img']['tmp_name'];
  6. if(move_uploaded_file($tmpname, dirname(__FILE__).'/img/'.$filename))
  7. {
  8. echo json_encode('上传成功');
  9. }
  10. else
  11. {
  12. $data = json_encode($_FILES);
  13. echo $data;
  14. }
  15. }
  16. ?>

例子,同样是利用curl不过这是利用ftp,代码如下:

  1. <?php
  2. $localfile = "php_homepage.txt";
  3. $fp = fopen ($localfile, "r");
  4. $arr_ip = gethostbyname(www.phpfensi.com);
  5. echo $arr_ip;
  6. $ftp = "ftp://".$arr_ip."/public_html/".$localfile;
  7. $ch = curl_init();
  8. curl_setopt($ch, CURLOPT_VERBOSE, 1);
  9. curl_setopt($ch, CURLOPT_USERPWD, '***:****');
  10. curl_setopt($ch, CURLOPT_URL, $ftp);
  11. curl_setopt($ch, CURLOPT_PUT, 1);
  12. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  13. curl_setopt($ch, CURLOPT_INFILE, $fp);
  14. curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
  15. $http_result = curl_exec($ch);
  16. $error = curl_error($ch);
  17. echo $error."<br>";
  18. $http_code = curl_getinfo($ch ,CURLINFO_HTTP_CODE);curl_close($ch);
  19. fclose($fp);
  20. ?>