In PHP, ftp_chdir() changes the current working directory on the FTP server to the folder you name.
It works like cd in a terminal. After it succeeds, any relative paths you give to functions such as ftp_get(), ftp_put() or ftp_nlist() are resolved from this new folder.
Syntax
Call ftp_chdir() with the values you need. Start with this line.
PHP
$ok = ftp_chdir($ftp, "/public_html/uploads");
Call
What it does
ftp_chdir($ftp, "/public_html")
Moves to an absolute directory path and returns true on success.
ftp_chdir($ftp, "images")
Moves into a sub folder relative to the current directory.
ftp_chdir($ftp, "..")
Moves up one level, similar to ftp_cdup().
From PHP 8.1 the first argument is an FTP\Connection object. ftp_chdir() raises a warning if the folder does not exist, so check the return value or use the @ operator carefully.
ftp_nlist() with a dot lists the contents of the current folder.
It returns an array of file and folder names.
foreach prints each name on its own line.
Frequently Asked Questions
It changes the current working directory on the FTP server. Later FTP calls with relative paths start from that folder.
PHP raises a warning when the server refuses to change into the folder, for example when it does not exist or you lack permission. Check the return value and handle the false case.
Yes. A path starting with a slash, like /public_html, is absolute. Without the slash it is relative to the current directory.
Use ftp_cdup($ftp) or ftp_chdir($ftp, '..'). Both move to the parent directory.
No. It only changes the folder on the remote FTP server. Use chdir() for the local PHP working directory.