FTP remoto de servidor para servidor com PHP

Neste artigo apresento os testes que fiz usando os recursos de FTP do PHP, avaliei e debuguei uma classe que encontrei no PHPClasses.org. Esta facilidade demonstra a riqueza de recursos que o PHP nos oferece.

[ Hits: 17.894 ]

Por: Roberto Francisco em 03/09/2003


Classe php_ftp_class.php



<?php
/*

From www.phpclasses.org
##########################
Class:
php_ftp_class
Short description:
Class that connects to a FTP server to work with files and directores.
Supplied by:
Name: Max V. Moiseenko <m.moiseenko at sys4tec dot com>
Country: Russian Federation
Home page: http://www.sys4tec.com/
License:
Unspecified (ask the author)
Groups:
Networking
Files and Directories
#############################

Changes and little bugs solveds:
Roberto Francisco - BobFrank
rsfranc@yahoo.com.br
22/08/2003 - SP/Brasil
Changelog:
srv2srv($from,$to) - new - Remote Upload Server to Server
function php_ftp_class - constructor class name changed
dir_list() - changed
rawlist_2_nlist($list) - new (added from php.net)
$mode (FTP_BINARY || FTP_ASCII) - changed

###############################

Class that connects to a FTP server to work with files and directores.
It features:
- connect to ftp server
- change current working dir
- create new empty file
- create new dir
- change access right to object
- send SITE command
- copy file
- move and rename file or dirs
- move uploaded file from TMP into CWD
- delete file or empty directory
- write into file

#################################

Methods descriptions - BobFrank contribution.

$FTP_HOST      = "localhost";
$FTP_USER      = "guest";
$FTP_PW       = "";
$FTP_ROOT_DIR = "/public_html/";

$ftp = new php_ftp_class($FTP_USER,$FTP_PW,$FTP_HOST,$FTP_ROOT_DIR);

$ftp->connect()                 # open connection [opt] supplied by constructor
$ftp->close()                  # close connection
$ftp->error($err_str="")           # error message
$ftp->cd($dir)                 # change current working dir
$ftp->mk_file($name)              # create new empty file
$ftp->mk_dir($name)              # create new dir
$ftp->set_perm($obj,$num)           # change access right to object
$ftp->site($cmd)                 # send SITE command
$ftp->copy($from,$to)              # copy file
$ftp->move($from,$to)              # move object
$ftp->move_uploaded_file($file_to_move,$file_name)  # move uploaded file from TMP into CWD
$ftp->rename($from,$to)           # rename object
$ftp->del($obj)                 # kill file or empty directory
$ftp->write($dest,$FILEDATA)        # write into file  
$ftp->get_perm($obj,$type='i')       # return access right of an object, at various formats
$ftp->dir_list()                 # print dir file list
$ftp->rawlist_2_nlist($list)         # rawlist to nlist
$ftp->srv2srv($from,$to)         # copy fopen(from) your server to ftp server

####################################
*/


class php_ftp_class{
  var $user;
  var $pw;
  var $host;
  var $root_dir;//root ftp dir of server
  var $con_id;//descriptor on ftp connection
  var $cwd;//current working dir
  var $ERR=true;//must object display ftp errors
  //var $FTP_MODE="FTP_ASCII";// FTP_ASCII | FTP_BYNARY
  var $FTP_MODE="FTP_BINARY"; // FTP_ASCII | FTP_BINARY
  
  

  //constr.
  //function my_ftp($user="guest",$pw="guest",$host="localhost",$root=""){
  function php_ftp_class($user="guest",$pw="guest",$host="localhost",$root=""){
    $this->host=$host;
    $this->user=$user;
    $this->pw=$pw;
    $this->root_dir=$root;
    if($this->connect()){
      
      //$this->cwd=ftp_pwd($this->con_id);
      $this->cd($this->root_dir);
    }
  }

  //connect to ftp server
  function connect(){
    if($this->con_id=ftp_connect($this->host)){
      if(ftp_login($this->con_id,$this->user,$this->pw))return true;
      else $this->error("User <b>"".$this->user.""</b> cannot login to host <b>"".$this->host.""</b>");
    }else $this->error("Connection with host <b>"".$this->host.""</b> not create!");
    return false;
  }

  //close ftp connection
  function close(){
    ftp_quit($this->con_id);
  }

  //print error messages
  function error($err_str=""){
    if($this->ERR)echo "[".$err_str."]<br>\n";
  }

  //change current working dir
  function cd($dir){
    if(!@ftp_chdir($this->con_id,$dir)){
      $this->error("Cannot view directory <b>"".$this->root_dir."/".$dir.""</b>!");
      return false;
    }
    $this->cwd=@ftp_pwd($this->con_id);
    return true;
  }

  //create new empty file
  function mk_file($name){
   $this->FTP_MODE=="FTP_BINARY" ? $mode=FTP_BINARY : $mode=FTP_ASCII;
    if(file_exists($this->root_dir."/".$this->cwd."/".$name)){
      $this->error("File <b>"".$this->root_dir."/".$this->cwd."/".$name.""</b> already exists!");
      return false;
    }else{
      if(!$tmpfile=tempnam("/tmp","phpftptmp")){
        $this->error("Can't create temp file?");
        return false;
      }elseif(!ftp_put($this->con_id,$name,$tmpfile,$mode)){
        $this->error("Can't create file <b>"".$this->root_dir."/".$this->cwd."/".$name.""</b>");
        unlink($tmpfile);
        return false;
      }
    }
    unlink($tmpfile);
    return true;
  }

  //create new dir
  function mk_dir($name){
    if(file_exists($this->root_dir."/".$this->cwd."/".$name)){
      $this->error("Directory <b>"".$this->root_dir."/".$this->cwd."/".$name.""</b> already exists!");
      return false;
    }elseif(!ftp_mkdir($this->con_id,$name)){
      $this->error("Cannot create directory <b>"".$this->root_dir."/".$this->cwd."/".$name.""");
      return false;
    }
    return true;
  }

  //change access right to object
  function set_perm($obj,$num){
    //CHMOD 444 ftp.php3
    if(!$this->site("CHMOD ".$num." ".$obj)){
      $this->error("Cannot change permitions of object <b>"".$this->root_dir."/".$this->cwd."/".$obj.""</b>");
      return false;
    }
    return true;
  }

  //send SITE command
  function site($cmd){
    if(!ftp_site($this->con_id, $cmd)){
      $this->error("Cannot send site command <b>"".$cmd.""</b>");
      return false;
    }
    return true;
  }
  
  //copy file
  function copy($from,$to){
   $this->FTP_MODE=="FTP_BINARY" ? $mode=FTP_BINARY : $mode=FTP_ASCII;    
    if(file_exists($this->root_dir."/".$to)){
      $this->error("Object <b>"".$this->root_dir."/".$to.""</b> already exists!");
      return false;
    }
    srand((double)microtime()*1000000);
    $tmpfile=dirname(tempnam('',''))."/phpftptmp.".rand();
    if(!copy($this->root_dir."/".$from,$tmpfile)){
      $this->error("Can't create temp file?");
      return false;
    }elseif(!ftp_put($this->con_id,$to,$tmpfile,$mode)){
      $this->error("File <b>"".$this->root_dir."/".$from.""</b> can not copied to <b>"".$this->root_dir."/".$to.""</b>!");
      return false;
    }
    return true;
  }

  //move object
  function move($from,$to){
    if(file_exists($this->root_dir."/".$to)){
      $this->error("Object <b>"".$this->root_dir."/".$to.""</b> already exists!");
      return false;
    }
    if(!ftp_rename($this->con_id,$from,$to)){
      $this->error("Cannot move object <b>"".$this->root_dir."/".$from.""</b> to <b>"".$this->root_dir."/".$to.""</b>");
      return false;
    }
    return true;
  }

  //rename object
  function rename($from,$to){
    if(file_exists($this->root_dir."/".$this->cwd."/".$to)){
      $this->error("Object <b>"".$this->root_dir."/".$this->cwd."/".$to.""</b> already exists!");
      return false;
    }elseif(!ftp_rename($this->con_id,$from,$to)){
      $this->error("Cannot rename object <b>"".$this->root_dir."/".$this->cwd."/".$to.""</b>");
      return false;
    }
    return true;
  }

  //kill file or empty directory
  function del($obj){
    if(is_dir($this->root_dir."/".$this->cwd."/".$obj)){
      if(!ftp_rmdir($this->con_id, $obj)){
        $this->error("Cannot delete directory <b>"".$this->root_dir."/".$this->cwd."/".$obj.""</b>");
        return false;
      }
    }elseif(is_file($this->root_dir."/".$this->cwd."/".$obj)){
      if(!ftp_delete($this->con_id, $obj)){
        $this->error("Cannot delete file <b>"".$this->root_dir."/".$this->cwd."/".$obj.""</b>");
        return false;
      }
    }else{
      $this->error("Removing object <b>"".$this->root_dir."/".$this->cwd."/".$obj.""</b> canceled!");
      return false;
    }
    return true;
  }

  //write into file
  function write($dest,$FILEDATA){
    if(!WIN){
      $old_perm=$this->get_perm($dest,'i');
      $this->set_perm($dest,"666");
    }
    $fd=fopen($this->root_dir."/".$this->cwd."/".$dest,"w");
    if(!fwrite($fd,$FILEDATA)){
      $this->error("Cannot write file <b>"".$this->root_dir."/".$this->cwd."/".$dest.""</b>");
      fclose($fd);
      if(!WIN)$this->set_perm($dest,"644");
      return false;
    }
    fclose($fd);
    if(!WIN)$this->set_perm($dest,"644");
    return true;
  }

  //move uploaded file from TMP into CWD
  function move_uploaded_file($file_to_move,$file_name){
   $this->FTP_MODE=="FTP_BINARY" ? $mode=FTP_BINARY : $mode=FTP_ASCII;    
    srand((double)microtime()*1000000);
    if(!$tmp_dir=get_cfg_var('upload_tmp_dir'))$tmp_dir=dirname(tempnam('',''));
    $tmpfile=$tmp_dir."/phpftptmp.".rand();
    if(!copy($file_to_move,$tmpfile)){
      $this->error("Can't create temp file?");
      unlink($file_to_move);
      return false;
    }elseif(!ftp_put($this->con_id,$this->cwd."/".$file_name,$tmpfile,$mode)){
      $this->error("Can't write file <b>"".$this->root_dir."/".$this->cwd."/".$file_name.""</b>");
      unlink($file_to_move);
      unlink($tmpfile);
      return false;
    }
    unlink($file_to_move);
    unlink($tmpfile);
    return true;
  }

  //return access right of an object, at various formats
  function get_perm($obj,$type='i'){
    $num=fileperms($obj);
    $s=array(07=>'rwx',06=>'rw-',05=>'r-x',04=>'r--',03=>'-wx',02=>'-w-',01=>'--x',00=>'---');
    $i=array(07=>'7',06=>'6',05=>'5',04=>'4',03=>'3',02=>'2',01=>'1',00=>'0');
    $b=array(
      07=>array(1,1,1),
      06=>array(1,1,0),
      05=>array(1,0,1),
      04=>array(1,0,0),
      03=>array(0,1,1),
      02=>array(0,1,0),
      01=>array(0,0,1),
      00=>array(0,0,0)
    );
    switch($type){
      case 'b':
        $ret['o']=$b[($num & 0700)>>6];
        $ret['g']=$b[($num &  070)>>3];
        $ret['a']=$b[($num &   07)   ];
        break;
      case 's':
        if($num & 0x1000)     $ret ='p';//FIFO pipe
        elseif($num & 0x2000) $ret.='c';//Character special
        elseif($num & 0x4000) $ret.='d';//Directory
        elseif($num & 0x6000) $ret.='b';//Block special
        elseif($num & 0x8000) $ret.='-';//Regular
        elseif($num & 0xA000) $ret.='l';//Symbolic Link
        elseif($num & 0xC000) $ret.='s';//Socket
        else $str.='?'; //UNKNOWN
        $ret.=$s[($num & 0700)>>6];
        $ret.=$s[($num &  070)>>3];
        $ret.=$s[($num &   07)   ];
        break;
      case 'i':
        $ret =$i[($num & 0700)>>6];
        $ret.=$i[($num &  070)>>3];
        $ret.=$i[($num &   07)   ];
        break;
    }
    return $ret;
  }
  
  //print dir file list
  function dir_list(){
    //ftp_nlist Returns a list of files in the given directory.
    //ftp_rawlist Returns a detailed list of files in the given directory.
    ?><table border=1 cellpadding=3 cellspacing=0><tr><td>Directories</td><td>Files</td></tr><?
   //  $contents=ftp_nlist($this->con_id, $this->cwd);
   $contents = ftp_rawlist($this->con_id, $this->cwd);
   $contents = $this->rawlist_2_nlist($contents);  
    
    $d_i=0;
    $f_i=0;
    sort($contents);
    
    for($i=0;$i<count($contents);$i++){
      $file_size=ftp_size($this->con_id,$contents[$i]);
      if(is_dir($this->root_dir.$contents[$i])){
        $nlist_dirs[$d_i]=$contents[$i];
        $d_i=$d_i+1;
      }
      else{
             $nlist_files[$f_i]=$contents[$i];
           $nlist_filesize[$f_i]=$file_size;
           $f_i=$f_i+1;    
      }
    }
    
    ?><tr><td><pre><?
    if(isset($nlist_dirs)){
       for($i=0;$i<count($nlist_dirs);$i++)echo $nlist_dirs[$i]."<br>";
   }
    ?></td><td><pre><?    
    if(isset($nlist_files)){      
       for($i=0;$i<count($nlist_files);$i++){
          echo $nlist_files[$i]          
          ." - ".(int)$nlist_filesize[$i]
          ."<br>";
      }
   }
    ?></td></tr></table><?
  }
  
  //rawlist to nlist - rawlist $list
  function rawlist_2_nlist($list){
     $newlist = array();            
     @reset($list);
     while (list(,$row) = @each($list))
     {
      $index = strrpos($row, " ");
          $newlist[] = substr($row, $index+1);
     }
     return $newlist;
  }
  
  //upload file from server to server (BobFrank)
  function srv2srv($from,$to){
   $from_fp = fopen($from,"r");
   if(!$from_fp){
      return false;
   }  
   $this->FTP_MODE=="FTP_BINARY" ? $mode=FTP_BINARY : $mode=FTP_ASCII;
     if(!@ftp_fput($this->con_id, $to, $from_fp, $mode)){
     $this->error("Cannot send file<b>"".$from." -> ".$to.""</b>");
      return false;
    }
    return true;
  }
}//end class ?>
Página anterior    

Páginas do artigo
   1. Procurando a solução
   2. Fazendo funcionar
   3. Classe php_ftp_class.php
Outros artigos deste autor
Nenhum artigo encontrado.
Leitura recomendada

Symfony Framework - Introdução

Organizando fotos de camêra digital

Organizando projetos com a classe FastTemplate (parte 1)

Relatórios com PHP e XSLT - Conceitos iniciais e utilização básica

Utilizando PHP para validar dados passados pelo usuário

  
Comentários
[1] Comentário enviado por fabio em 03/09/2003 - 00:05h

Olá bobfrank, gostei da foto do seu perfil! :)
Esse livro PHP Programming é um ícone, foi ele que me introduziu nesta belíssima linguagem também, muito bom.

[2] Comentário enviado por ygorth em 17/02/2004 - 01:31h

Otimo artigo. Vou testar..

[3] Comentário enviado por coffani em 28/07/2008 - 23:58h

Muito bom. Vou testar pois estou precisando de uma classe dessas em uma aplicação que estou desenvolvendo

Parabéns

[4] Comentário enviado por wesleysimplicio em 28/01/2013 - 08:42h

Muito bem elaborado o Artigo, está de parabéns !


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts