Created
June 25, 2014 15:50
-
-
Save Teqqles/be92ed596fbf302d0265 to your computer and use it in GitHub Desktop.
Delete all files from a given FTP directory using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ftpDelete { | |
const TEMP_DIRECTORY = '/Temp'; | |
const PASSIVE = true; | |
const ACTIVE = false; | |
private $connection; | |
private $loggedIn = false; | |
public function __construct( $server, $username, $password, $mode ) { | |
$this->connection = ftp_connect( $server ); | |
$this->loggedIn = ftp_login( $this->connection, $username, $password ); | |
if ( $this->loggedIn ) { | |
ftp_pasv ( $this->connection , $mode ); | |
} | |
} | |
public function deleteAllFromDirectory( $directory ) { | |
if ( !$this->loggedIn ) { | |
return false; | |
} | |
$fileList = ftp_nlist( $this->connection, $directory ); | |
if( $fileList === false ) { | |
return false; | |
} | |
foreach( $fileList as $fileToRemove ) { | |
$this->deleteFile( $this->appendTrailingSlash( $directory ) . $fileToRemove ); | |
} | |
return true; | |
} | |
private function appendTrailingSlash( $directory ) { | |
return preg_replace( '@([^/])$@', '\1/', $directory ); | |
} | |
private function deleteFile( $filename ) { | |
if ( !$this->loggedIn ) { | |
return false; | |
} | |
if ( ftp_delete( $this->connection, $filename ) ) { | |
return true; | |
} | |
return false; | |
} | |
public function closeConnection() { | |
if ( !$this->connection ) { | |
return; | |
} | |
ftp_close( $this->connection ); | |
} | |
} | |
$ftp = new ftpDelete( 'ftp.server.address', 'username', 'password', ftpDelete::PASSIVE ); | |
$ftp->deleteAllFromDirectory( ftpDelete::TEMP_DIRECTORY ); | |
$ftp->closeConnection(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment