Last active
December 10, 2015 19:18
-
-
Save stojg/4480085 to your computer and use it in GitHub Desktop.
Quick recipe on how to the latest .zip file from a ftp server
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 | |
$ftpConnection = array( | |
'host' => 'server.co.nz', | |
'username' => 'username', | |
'password' => 'secret-password' | |
); | |
// set up basic connection | |
$connection = ftp_connect($ftpConnection['host']); | |
if(!$connection) { | |
throw new Exception('Can\'t connect to host: "'.$ftpConnection['host'].'"'); | |
} | |
echo 'login'.PHP_EOL; | |
$loginResult = ftp_login($connection, $ftpConnection['username'], $ftpConnection['password']); | |
if(!$loginResult) { | |
throw new Exception('Can\'t login to host: "'.$ftpConnection['host'].'" with user "'.$ftpConnection['username'].'"'); | |
} | |
echo 'listing files'.PHP_EOL; | |
$files = ftp_nlist($connection, ''); | |
if(!$files) { | |
throw new Exception('Can\'t find a list of file on host: "'.$ftpConnection['host'].'"'); | |
} | |
// Only choose from .zip files | |
$files = array_filter($files, function($file) { | |
$dotted = explode('.', $file); | |
$suffix = array_pop($dotted); | |
if(strtolower($suffix) == 'zip') { | |
return true; | |
} | |
}); | |
natcasesort($files); | |
$remoteFile = array_pop($files); | |
$localFile = $remoteFile; | |
echo 'downloading '.$remoteFile.PHP_EOL; | |
$handle = fopen($localFile, 'w'); | |
if(!ftp_fget($connection, $handle, $remoteFile, FTP_BINARY, 0)) { | |
throw new Exception('Failed downloading remote file'.$remoteFile,' to local file '.$localFile); | |
} | |
ftp_close($connection); | |
fclose($handle); | |
echo 'unzipping '.$remoteFile.PHP_EOL; | |
$destinationFolder = '/tmp/'; | |
$zip = new ZipArchive(); | |
if ($zip->open($localFile) === TRUE) { | |
$zip->extractTo($destinationFolder); | |
$zip->close(); | |
} else { | |
throw new Exception('Failed to unzip '.$localFile,' to directory "'.$destinationFolder.'"'); | |
} | |
return $destinationFolder.$localFile; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment