Building An FTP Client With PHP - Retrieving a File
(Page 4 of 7 )
Thanks to PHP and the way that the FTP protocol is wrapped into its ftp_xxx functions, it's also extremely easy to retrieve a file from a remote FTP server using the ftp_get function. Its signature is shown below:
bool ftp_get ( resource ftp_stream, string local_file, string remote_file, int mode) On success, ftp_get returns true. On failure, it returns false. Details of each parameter that it requires are shown below:
- ftp_stream: The resource generated by a call to ftp_connect.
- local_file: The name of the file where the remote file will be saved to.
- remote_file: The name of the remove file which will be copied.
- mode: The transfer mode that should be used to copy the file from the FTP server to the local file. This should be either one of PHP’s predefined constants: FTP_ASCII or FTP_BINARY.
Using ftp_get, let's connect to a remote FTP server, retrieve a text file, and then display this text file in the browser:
if(@ftp_chdir($conn, "/bussys"))
{
$gotFile = @ftp_get($conn, "c:/thefile.txt", "readme.txt", FTP_ASCII);
if($gotFile)
{
$fp = fopen("c:/thefile.txt", "rb");
while($data = fgets($fp, 1024))
{
echo $data;
}
@fclose($fp);
}
else
{
echo "ERROR: Couldn't get file";
}
}
else
{
echo "ERROR: Couldn't change directories";
} The example above shows just how easy it is to retrieve a file from a remote FTP server. Just as easily as we can download a file, we can also send one to the FTP server. The ftp_put function helps us accomplish this:
bool ftp_put ( resource ftp_stream, string remote_file, string local_file, int mode) The parameters are exactly the same as ftp_get, so let's jump straight into an example. This time, however, I will FTP into my Windows 2000 server machine, which has FTP setup. The exact sample principles apply for any FTP server, so just change the server name and login details when you’re testing the code:
<?php
$ftpServer = "s3web";
$ftpUser = "mitchell";
$ftpPass = "xxxxx";
$conn = @ftp_connect($ftpServer);
$login = @ftp_login($conn, $ftpUser, $ftpPass);
$putFile = @ftp_put($conn, "/newimage.gif", "c:/mitch.gif", FTP_BINARY);
if($putFile)
echo "File uploaded OK.";
else
echo "File upload failed.";
ftp_quit($conn);
?> And it really is that easy. Before we move on and create our own basic FTP application, I just want to mention the ftp_systype command, which returns a string indicating which type of operating system your FTP server is running. The following code returns "Windows_NT" when I connect to my Windows 2000 FTP server:
...
$conn = @ftp_connect($ftpServer);
$login = @ftp_login($conn, $ftpUser, $ftpPass);
echo ftp_systype($conn);
...Next: Building an FTP App >>
More PHP Articles
More By Mitchell Harper