Snippet Name: FTP via PHP
Description: A lot of people have asked for VERY simple FTP functionality with PHP, so here it is.
This class was designed with very simplistic transfers in mind. You simple create the class,
get/send a file and then 'kill()' the object. It's that simple. I you find it useful.
Example:
//Get a file
require("class.ftp.php"); //include library
$f=new PHP_FTP('ftp.somesite.com', 'username', 'password'); //specify connect info
$f->get('html/test.txt', 'c:/php/ftp/blah.txt'); //yes, tested on Windows
$f->kill(); //optional destroy class method
//Send a file
require("class.ftp.php");
$f=new PHP_FTP('ftp.somesite.com', 'username', 'password', 21); //optional port as 4th arg
$f->send('c:/php/ftp/blah.txt', 'html/test.txt'); //yes, tested on Windows
$f->kill();
//how to test for completion
if(!$f->send('c:/php/ftp/blah.txt', 'html/test.txt')){
echo "File sent successfully!";
}else{
echo "Error sending file.";
}
Notes:
Remember to have all permissions set to their appropriate settings before using this class
Comment: (none)
Language: PHP
Highlight Mode: PHP
Last Modified: March 01st, 2009
|
<?PHP
CLASS PHP_FTP{
VAR $server='';
VAR $username='';
VAR $password='';
VAR $port=21;
VAR $remote_dir='';
FUNCTION PHP_FTP($server, $username='anonymous', $password='[email protected]', $port=21){
$this->server=$server;
$this->username=$username;
$this->password=$password;
$this->port=$port;
}
//exterior
FUNCTION send($filename='', $save_as='', $passive=TRUE){
$conn=$this->return_connection() or DIE;
@FTP_PASV($conn, $passive);
$this->set_remote_dir(FTP_PWD($conn));
IF(!FTP_PUT($conn, $save_as, $filename, FTP_BINARY)){
@FTP_QUIT($this->conn);
RETURN FALSE;
}ELSE{
@FTP_QUIT($this->conn);
RETURN TRUE;
}
RETURN TRUE;
}
FUNCTION get($filename='', $save_as='', $passive=TRUE){
$conn=$this->return_connection() or DIE;
@FTP_PASV($conn, $passive);
$this->set_remote_dir(FTP_PWD($conn));
IF(!FTP_GET($conn, $save_as, $this->remote_dir.$filename, FTP_BINARY)){
@FTP_QUIT($this->conn);
RETURN FALSE;
}ELSE{
@FTP_QUIT($this->conn);
RETURN TRUE;
}
}
FUNCTION kill(){
IF($this->conn)
$this->disconnect();
UNSET($this);
}
//interior
FUNCTION return_connection(){
$conn_id = @FTP_CONNECT($this->server, $this->port) or DIE("Could not connect to FTP");
$login_result = @FTP_LOGIN($conn_id, $this->username, $this->password) or DIE("Could not login to FTP");
RETURN $conn_id;
}
FUNCTION set_remote_dir($dir){
$x = SUBSTR($dir, (STRLEN($dir)-1));
IF($x != "/" && $x != "\\")
$dir.="/";
$this->remote_dir=$dir;
}
}
?>
/* example */
require("class.ftp.php");
$f=new PHP_FTP('ftp.somesite.com', 'username', 'password', 21); //optional port as 4th arg
$f->send('c:/php/ftp/blah.txt', 'html/test.txt'); //yes, tested on Windows
$f->kill();
|