Looping Through an FTP Directory Using PHP

July 13th, 2011 - Posted by Steve Marks to PHP, Web Development.

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 = "";
$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.

Tags: ,
This entry was posted on Wednesday, July 13th, 2011 at 9:15 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first