Building An FTP Client With PHP - The GetFile function
(Page 6 of 7 )
GetFile makes use of the ftp_get command to retrieve one selected file from the remote FTP server. After the call to ftp_get, a status message is displayed at the top of the screen indicating whether or not the file was downloaded successfully: a yellow message is shown on success, and a red one on failure.
GetFile starts out by working out where the file should be saved to:
function GetFile()
{
$conn = DoConn();
$currDir = "";
// Get the name of the current directory
if(isset($_GET["currFile"]))
{
$currFile = $_GET["currFile"];
// We need to work out the name of the file
// by stripping away the path, etc
$localFile = strrev($currFile);
$localFile = substr($localFile, 0, strpos($localFile, "/"));
$localFile = strrev($localFile);
$localFile = "___$localFile"; As mentioned earlier, the name of the file is prefixed with three underscores and saved to the root directory on your local machine. The reason I've prefixed the files with three underscores is so that you don't overwrite any important system files by accidentally download files with the same name from the remote server.
GetFile is basically just one call to ftp_get with some error handling:
if(@ftp_get($conn, $localFile, $currFile, FTP_BINARY))
{
// Success
}
else
{
// Failure
} If the file was retrieved OK, then a message like the following is shown at the top of the screen:
On the other hand, if something goes wrong then a message like the one shown below is displayed:
Now, at this point we've taken a look at both the ShowFiles and GetFile functions. If you've never worked with PHP and FTP before, then let me set this challenge for you:
I'm not going to provide you with the code for the PutFile, RenameFile or DeleteFile functions. Instead, head on over to
the PHP FTP reference page and see if you can workout how to accomplish these functions using PHP's built-in FTP functionality. It's actually quite easy to do, and by doing so you will help yourself to become a better coder.
Next: Conclusion >>
More PHP Articles
More By Mitchell Harper