Tuesday 17 July 2018

Looping Through an FTP Directory Using PHP

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:

  1. // Initialise the connection parameters  
  2. $ftp_server = "123.123.123.123";  
  3. $ftp_username = "ftpuser";  
  4. $ftp_password = "ftppass";  
  5.   
  6. // Create an FTP connection  
  7. $conn = ftp_connect($ftp_server);  
  8.   
  9. // Login to FTP account using username and password  
  10. $login = ftp_login($conn$ftp_username$ftp_password);  
  11.   
  12. // Get the contents of the current directory  
  13. // Change the second parameter if wanting a subdirectories contents  
  14. $files = ftp_nlist($conn".");  
  15.   
  16. // Loop through $files  
  17. foreach ($files as $file) {  
  18.   
  19.     // Do something with the file here.   
  20.   
  21.     // For now we'll echo the filenames in a list  
  22.     echo $file."<br />";  
  23.   
  24. }  
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