PHP: Changing the FTP directory.

This is a beginner’s PHP tutorial on how to connect to a FTP server and change the directory. I will also show you how to list all of the files in that directory.

Take a look at the following code:

In the example above, we:

  1. Logged into our 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 code above, you should see that an array of filenames have been dumped out onto the screen.

Facebook Comments