Looping Through an FTP Directory Using PHP
If you’re a website developer you’ll probably have countless hours of experience using FTP, from putting sites live, renaming files, deleting files and more. This is made easy through using an FTP client installed on your machine. The process can also be just as simple by using PHP through a whole host of readily available functions when needing to manipulate an FTP directories contents within a PHP script.
Today I want to focus our attention on obtaining and looping through the contents of an FTP directory using PHP through use of the function ftp_nlist(). Let’s take a look at a simple example of how to achieve this:
- // Initialise the connection parameters
- $ftp_server = "123.123.123.123";
- $ftp_username = "ftpuser";
- $ftp_password = "ftppass";
- // Create an FTP connection
- $conn = ftp_connect($ftp_server);
- // Login to FTP account using username and password
- $login = ftp_login($conn, $ftp_username, $ftp_password);
- // Get the contents of the current directory
- // Change the second parameter if wanting a subdirectories contents
- $files = ftp_nlist($conn, ".");
- // Loop through $files
- foreach ($files as $file) {
- // Do something with the file here.
- // For now we'll echo the filenames in a list
- echo $file."<br />";
- }
In the above code we are connecting to the FTP server, logging in, obtaining the list of files within the current directory and looping through them.
0 comments:
Post a Comment