PHP: Changing the FTP directory.

In this tutorial, we are going to show you how to change an FTP directory using PHP.

We will also show you how to list all of the files in that directory.

Take a look at the following code:

//Your FTP server connection details.
$host = '';
$username = 'ftp_username';
$password = 'ftp_password';

//The path of the directory that you want to list all files in.
$directory = '/test';

//Attempt to connect.
$conn = @ftp_connect($host);

//If the connection failed, throw an Exception.
if($conn === false){
    throw new Exception('Failed to connect to FTP server at ' . $host);

//Log into the FTP server.
$loggedIn = ftp_login($conn, $username, $password);

//If the login failed, throw an Exception.
if($loggedIn === false){
    throw new Exception('Could not login to FTP server!');

//Attempt to change the directory.
$changedDirectory = ftp_chdir($conn, $directory);

//If that failed, throw an Exception.
if($changedDirectory === false){
    throw new Exception('Could not change FTP directory to: ' . $directory);

//Now that we've changed the FTP directory, get a list
//of files in the current directory.
$fileList = ftp_nlist($conn, '.');

//var_dump the file list

In the example above:

  1. We logged into the FTP server using PHP. Note that you will need to change the FTP details at the top of the script to match your own. Otherwise, PHP will fail to connect and throw an Exception.
  2. Once we successfully logged into our FTP server, we changed the directory using the ftp_chdir function. If the specified folder does not exist on the server, ftp_chdir will return a boolean FALSE value and omit a warning message. In our script above, we throw an Exception if ftp_chdir returns FALSE. This is because there is no point in trying to list the files of a directory that doesn’t exist.
  3. After our script has successfully navigated to the new directory, we then retrieve a list of files by using the ftp_nlist function. The ftp_nlist function will return an array of filenames. In our PHP code above, we set the second parameter of ftp_nlist to “.” because we want to retrieve the contents of the current directory. i.e. The FTP directory that we just changed to.

And that’s it!

If you run the script above, you will see that it prints an array of filenames out onto the page.