Bonjour à tous, voici un objet Ftp en PHP5 qui vous permet de vous connecter sur un ftp distant, lire, déplacer, supprimer, rechercher un fichier à partir d'un mot complet ou d'une abréviation (utile pour des mises à jours sur fichiers générés automatiquement).
La classe a été créee de sorte à être très simple d'usage et accessible.
Pour toutes améliorations ou commentaires, n'hésitez pas à me faire vos propositions :).
PS: Télécharger la source pour éviter les espaces entre certains mots et variables qui se glissent lors du dépot du code source.
Source / Exemple :
<?php
########################################################################################
########################################################################################
###
### Ftp class, allows you to read, search, move, delete a file on a ftp server.
###
### @name intyFtp
### @author Edoaurd Kombo <edouard.kombo@live.fr>
###
########################################################################################
########################################################################################
class intyFtp{
protected $_path = false; //Path to go on the ftp
protected $_ftp = false; //Ftp connexion
protected $_localFile = false;
protected $_file = false;
protected $_server;
protected $_user;
protected $_pass;
function __construct(){}
function __destruct(){}
///////////////////////////////////////////
///////////////////////////////////////////
// SETTERS
///////////////////////////////////////////
///////////////////////////////////////////
private function setPath($path){ //On récupère le contenu du répertoire
return $this->_path = $path;
}
private function setFile($file){ //On récupère le contenu du répertoire
return $this->_file = $file;
}
private function setPassiveMode($mode){ //turn passive mode on/off for local ftp
try{
$getMode = ($mode) ? 'on' : 'off' ;
if(!ftp_pasv($this->_ftp, $mode)){
$error = 'Unable to turn passive mode "'.$getMode.'".';
throw new Exception($error);
}
} catch(Exception $e) {
echo 'Exception caught by method "'.__FUNCTION__.'": '.$e->getMessage()."\n";
}
}
///////////////////////////////////////////
///////////////////////////////////////////
// GETTERS
///////////////////////////////////////////
///////////////////////////////////////////
private function getList(){ //On récupère le contenu du répertoire
try{
if($this->_path){
return ftp_nlist($this->_ftp , $this->_path);
} else {
$error = 'Unable to connect to server "'.$server.'".';
throw new Exception($error);
}
} catch(Exception $e) {
echo 'Exception caught by method "'.__FUNCTION__.'": '.$e->getMessage()."\n";
}
}
///////////////////////////////////////////
///////////////////////////////////////////
// PUBLIC METHODS
///////////////////////////////////////////
///////////////////////////////////////////
function set($args){
switch($args[0]){
case 'path': $result = $this->setPath($args[1]);
break;
case 'file': $result = $this->setFile($args[1]);
break;
case 'passive_mode': $result = $this->setPassiveMode($args[1]);
break;
}
return $result;
}
function get($args){
switch($args[0]){
case 'list': $result = $this->getList();
break;
}
return $result;
}
function connect($server, $user, $pass){
try {
$this->_server = $server;
$this->_user = $user;
$this->_pass = $pass;
$this->_ftp = ftp_connect($this->_server);
if($this->_ftp){
if(!ftp_login($this->_ftp , $user , $pass)){
$error = 'Unable to login to server "'.$server.'". Please ensure identifiers are correct.';
throw new Exception($error);
}
} else {
$error = 'Unable to connect to server "'.$server.'".';
throw new Exception($error);
}
} catch(Exception $e) {
echo 'Exception caught by method "'.__FUNCTION__.'": '.$e->getMessage()."\n";
}
}
function search($order){ //Search a file on the ftp
//$order = 1 => growing
//$order = 0 => descending
$filesList = $this->getList(); //Get file lists in directory $this->_path
$result = array();
$exists = false;
//If the file exists in the directory
foreach($filesList as $key => $val){
if($val == $this->_path.$this->_file){
$exists = true;
$val = str_replace($this->_path , '' , $val);
array_push($result , $val);
}
}
//If the file doesn't exists in the directory, we search for a similar file in growing or descending order
if(!$exists){
$wordLength = strlen($this->_path.$this->_file);
foreach($filesList as $key => $val){
$thisWord = substr($val, 0, $wordLength);
if($thisWord == $this->_path.$this->_file){
$exists = true;
$val = str_replace($this->_path , '' , $val);
array_push($result , $val);
}
}
}
//We now choose the corresponding file or not
try{
if($exists){
if(count($result) >= 1){
return $this->_file = ($order == 1) ? max($result) : min($result); //Min or max value of the array
} else {
return $this->_file;
}
} else {
$error = 'The file has not been found in directory "'.$this->_path.'".';
throw new Exception($error);
}
} catch(Exception $e) {
echo 'Exception caught by method "'.__FUNCTION__.'": '.$e->getMessage()."\n";
}
}
function move($localFile){ //Transfer a local file on ftp_server
try{
//Tant que le fichier n'est pas uploadé sur le serveur, on ne fait rien d'autre
if(!ftp_put($this->_ftp , $this->_path.$this->_file , $localFile , FTP_BINARY)){
$error = 'The file has not been found in directory "'.$this->_path.'".';
throw new Exception($error);
}
} catch(Exception $e) {
echo 'Exception caught by method "'.__FUNCTION__.'": '.$e->getMessage()."\n";
}
}
function read($file){ //We read content of a file by Ftp
$thisFile = (!empty($file)) ? $file : $this->_path.$this->_file;
try{
$read = file_get_contents('ftp://'.$this->_user.':'.$this->_pass.'@'.$this->_server.'/'.$thisFile.'');
if(!$read){
$error = 'Unable to read file "'.$thisFile.'" on server "'.$this->_server.'".';
throw new Exception($error);
} else {
return $read;
}
} catch(Exception $e){
echo 'Exception caught by method "'.__FUNCTION__.'": '.$e->getMessage()."\n";
}
}
function delete($file){ //Delete file on ftp
$thisFile = (!empty($file)) ? $file : $this->_path.$this->_file ;
try{
if(!ftp_delete($this->_ftp, $thisFile)){
$error = 'Unable to read file "'.$thisFile.'" on server "'.$this->_server.'".';
throw new Exception($error);
}
} catch(Exception $e){
echo 'Exception caught by method "'.__FUNCTION__.'": '.$e->getMessage()."\n";
}
}
function close(){ //Disconnect from FTP
try{
if(!ftp_close($this->_ftp)){
$error = 'Impossible de se déconnecter du serveur ftp.';
throw new Exception($error);
}
} catch(Exception $e){
echo 'Exception caught by method "'.__FUNCTION__.'": '.$e->getMessage()."\n";
}
}
}
Conclusion :
//Application du code source
$ftp = new intyFtp();
$ftp->connect('server', 'user', 'pass');
//OPTIONAL
$ftp->set(array('passive_mode' , true));
//OPTIONAL
//Move a file into a ftp server
$ftp->set(array('path' , 'www/localStorage/')); //Set corresponding path on the ftp server
$ftp->set(array('file' , 'mytest.csv')); //Set the name of the file to be created
$ftp->move('a.csv'); //File on the local server to move to ftp server
$ftp->close();
//Search a file with an uncomplete filename
$ftp->set(array('path' , 'www/localStorage/')); //Set corresponding path on the ftp server
$ftp->set(array('file' , 'facturation')); //Set the name of the file to search (complete or uncomplete)
$file = $ftp->search(1); //Search a file starting with filename in the corresponding path (1 => get the file by growing order; 0 => get the file by descending order)
$ftp->close();
//Delete file on ftp server
$ftp->set(array('path' , 'www/localStorage/')); //Set corresponding path on the ftp server
$ftp->set(array('file' , 'facturation')); //Set the name of the file to search (complete or uncomplete)
$file = $ftp->search(1); //Search a file starting with filename in the corresponding path (1 => get the file by growing order; 0 => get the file by descending order)
$ftp->set(array('file' , $file)); //We define new filename
$ftp->delete(NULL); //We delete the corresponding filename (You can directly set the name of the file to delete on the ftp server)
$ftp->close();
//read file on ftp server
$ftp->set(array('path' , 'www/localStorage/')); //Set corresponding path on the ftp server
$ftp->set(array('file' , 'facturation')); //Set the name of the file to search (complete or uncomplete)
$file = $ftp->search(1); //Search a file starting with filename in the corresponding path (1 => get the file by growing order; 0 => get the file by descending order)
$ftp->set(array('file' , $file)); //We define new filename
echo $ftp->read(NULL); //We read the content of the file we defines (You can directly set the name of the file to read on the ftp server)
$ftp->close();
Vous n'êtes pas encore membre ?
inscrivez-vous, c'est gratuit et ça prend moins d'une minute !
Les membres obtiennent plus de réponses que les utilisateurs anonymes.
Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.
Le fait d'être membre vous permet d'avoir des options supplémentaires.