Stream Me Up, Scotty! (part 1) - ...In With The New (
Page 3 of 9 )
Initiating an FTP
connection in PHP follows the same basic principles: open an FTP connection,
send authentication information, and then use built-in PHP functions to navigate
through directories or transfer files. Let's take a look at the PHP version of
the session you just saw.
<?
// connect to FTP server
$conn = ftp_connect("ftp.server.com");
// log in with username and password
ftp_login($conn, "john", "doe");
// get remote system type
ftp_systype($conn);
// obtain file listing
$filelist = ftp_nlist($conn, ".");
// download file
ftp_get($conn, "data.zip", "data.zip", FTP_BINARY);
// close connection
ftp_quit($conn);
?>
Let's go through this step by step:
In order to
initiate an FTP connection, PHP offers the ftp_connect() function, which takes a
host name and port number as parameters. In the example above, the host name is
"ftp.server.com"; since a port is not specified, PHP will attempt a connection
to the default FTP port, 21.
The ftp_connect() function returns a handle
for the FTP connection if successful; this handle is used by all subsequent FTP
functions.
<?
// connect to FTP server
$conn = ftp_connect("ftp.server.com");
?>
Once connected, the ftp_login() function is used to send the
FTP server a user name and password. As you can see, ftp_login() also uses the
handle returned by ftp_connect() to ensure that the authentication information
is transmitted to the correct server.
<?
// log in with username and password
ftp_login($conn, "john", "doe");
?>
At this point, you can begin playing with some of the other
functions available to you, specifically those that provide you with system
information and directory listing (they're covered in detail on the next
page).
Once you're finished, it's important that you remember to close
your FTP session with ftp_quit().
<?
// close connection
ftp_quit($conn);
?>
This article copyright Melonfire
2000. All rights reserved.