+5

FTP Remoto de Servidor para Servidor

criado por Roberto Francisco em 23/08/2003 8:43pm

<?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 &quot;".$this->user."&quot; cannot login to host &quot;".$this->host."&quot;");
    }else $this->error("Connection with host &quot;".$this->host."&quot; 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 &quot;".$this->root_dir."/".$dir."&quot;!");
      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 &quot;".$this->root_dir."/".$this->cwd."/".$name."&quot; 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 &quot;".$this->root_dir."/".$this->cwd."/".$name."&quot;");
        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 &quot;".$this->root_dir."/".$this->cwd."/".$name."&quot; already exists!");
      return false;
    }elseif(!ftp_mkdir($this->con_id,$name)){
      $this->error("Cannot create directory &quot;".$this->root_dir."/".$this->cwd."/".$name."&quot;");
      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 &quot;".$this->root_dir."/".$this->cwd."/".$obj."&quot;");
      return false;
    }
    return true;
  }

  //send SITE command
  function site($cmd){
    if(!ftp_site($this->con_id, $cmd)){
      $this->error("Cannot send site command &quot;".$cmd."&quot;");
      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 &quot;".$this->root_dir."/".$to."&quot; 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 &quot;".$this->root_dir."/".$from."&quot; can not copied to &quot;".$this->root_dir."/".$to."&quot;!");
      return false;
    }
    return true;
  }

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

  //rename object
  function rename($from,$to){
    if(file_exists($this->root_dir."/".$this->cwd."/".$to)){
      $this->error("Object &quot;".$this->root_dir."/".$this->cwd."/".$to."&quot; already exists!");
      return false;
    }elseif(!ftp_rename($this->con_id,$from,$to)){
      $this->error("Cannot rename object &quot;".$this->root_dir."/".$this->cwd."/".$to."&quot;");
      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 &quot;".$this->root_dir."/".$this->cwd."/".$obj."&quot;");
        return false;
      }
    }elseif(is_file($this->root_dir."/".$this->cwd."/".$obj)){
      if(!ftp_delete($this->con_id, $obj)){
        $this->error("Cannot delete file &quot;".$this->root_dir."/".$this->cwd."/".$obj."&quot;");
        return false;
      }
    }else{
      $this->error("Removing object &quot;".$this->root_dir."/".$this->cwd."/".$obj."&quot; 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 &quot;".$this->root_dir."/".$this->cwd."/".$dest."&quot;");
      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 &quot;".$this->root_dir."/".$this->cwd."/".$file_name."&quot;");
      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&quot;".$from." -> ".$to."&quot;");
      return false;
    }
    return true;
  }
}//end class
?>

Para a versão mais atualizada dessa classe, por favor procure no site http://phpclasses.org

Comentários:

Mostrando 1 - 7 de 7 comentários
Qual a linha que eu devo colocar no .php para que ele execute os comandos e onde eu configuro as infos como path de envio?
12/09/2004 7:32am (~20 anos atrás)

Ola

esta é a variavel de cotação

$file
$boot_not)&=not

bom desenvolvi um novo script muito impotate para conexao FTP segura no PHP 4.0 qualquer duvida de mande um e-mail...

$if
$file_protocol
$transfer ()input_combox
$tester tk&¨*
"aqui usuario FTP" = ftp.seudominio.com "pega" $ftp
senha!" aqui a senha "suasenhaaqui" $senha

!!!¨¨¨conection
open_!14145162121-seconts.php
open_list.php
open_cmd_777
dir copy
file protocol
26/11/2003 12:38pm (~21 anos atrás)

Exelente artigo...
esse código pode ajudar e muito na vida de um progamador quando quer mudar de servidor...
03/09/2003 6:13pm (~21 anos atrás)

Olá Marco,
A variavel $files vem da transformação do array f[] na função:
foreach ($f as $files)

Quanto a sua necessidade, passo um exemplo retirado da php.net que mostra como fazer:
####################################
kiwo1 at yahoo dot com
28-Aug-2002 12:05
Friends,
If you wanna upload files from your harddisk by a form to a specified ftp this sample can help you...
First of all create the form:
<html>

<body marginwidth=4 marginheight=4 topmargin=4 leftmargin=4 bgcolor=white vlink="#0000ff" link="#0000ff">

<form name="Attachments" method=POST action="sendimage.php" enctype="multipart/form-data">

<input type=hidden name=box value="">

<tr>
<td nowrap width="1%">&nbsp;&nbsp;Image:</td>
<td colspan=2>
<input type=file name=source_file size=20> <br>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

</td>
</tr>
<input type=submit name=btnSubmit value=Submit size=20 style="border: 1px solid #0000FF"></form>
</body>
</html>

The critical point in this form is the usage of enctype="multipart/form-data"
If you don't use this part your upload operations won't work.
Then u must create sendimage.php as follows:

<?php

$ftp_server='190.148.20.201';//serverip
$conn_id = ftp_connect($ftp_server);


// login with username and password
$user="username";
$passwd="*****";
$login_result = ftp_login($conn_id, $user, $passwd);

// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
die;
} else {
echo "<br>Connected to $ftp_server, for user $user<br>";
}
//directorylike /www.velibaba.com/images
ftp_chdir($conn_id, "www.velibab.com");
ftp_chdir($conn_id, "compimages");

//$destination_file=ftp_pwd($conn_id);

$destination_file="x.jpg";
echo ("<br>");
print $destination_file;

echo ("<br>");

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}

// close the FTP stream
ftp_close($conn_id);
?>

In this example code $source_file is the path of the file in your disk, and destination file is the name of the uploaded file in ftpserver.
In this code I use ftp_chdir to give the path of the
uploaded file within ftpserver..
For your questions about all categories of PHP my email:kiwo1@yahoo.com
c u...
##########################################
Espero ter ajudado,
Roberto
03/09/2003 5:40pm (~21 anos atrás)

Marco disse:
Da onde vem o valor da variavel $files?
Nao seria $file?

Codigo:
if ($ftp->srv2srv($LOCAL_SERVER_DIR . $files, $files)) {


Estou perguntando isso porque estou fazendo um script que envia arquivos via FTP, user2server e vi que a funcao para upload

ftp_put($conn_id, "$arqServidor", "$arqLocal", FTP_ASCII);

Precisa do arquivo de origem e o de destino.
Como faco para colocar somente um campo no formulario de envio (o arquivo de origem) ?
Ex:
origem: D:\Imagens\vasco.jpg
destino: vasco.jpg

Eu teria q manipular a string $arqServidor?

Obrigado,


Marco Modesto.
03/09/2003 11:58am (~21 anos atrás)

Obrigado Alessander,
Desejei colocar a alteração lá, mas deveria preencher formulários e tal que enviei um e-mail para o Max V. Moiseenko o criador da classe.
Então, coloquei minha contribuição na php.net em http://br2.php.net/manual/en/function.ftp-fput.php
Obtigado!
26/08/2003 7:17am (~21 anos atrás)

Parabéns pelo artigo, nunca pensei na possibilidade de fazer tal operação e pelo que li é muito simples.

Você colocou no phpclasses a modificação que você fez? Seria muito interessante.

Obrigado, Alessander
26/08/2003 3:48am (~21 anos atrás)

Novo Comentário:

(Você pode usar tags como <b>, <i> ou <code>. URLs serão convertidas para links automaticamente.)