How can the ftp_chdir function be utilized to navigate to a specific directory before uploading files in PHP?
When uploading files using FTP in PHP, you may need to navigate to a specific directory on the remote server before uploading the files. This can be achieved by using the ftp_chdir function to change the current directory on the FTP server.
// Connect to FTP server
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$conn_id = ftp_connect($ftp_server);
ftp_login($conn_id, $ftp_user, $ftp_pass);
// Change directory
$directory = '/path/to/directory';
if (ftp_chdir($conn_id, $directory)) {
echo "Changed directory to $directory\n";
} else {
echo "Failed to change directory\n";
}
// Upload files
$file = 'local_file.txt';
ftp_put($conn_id, $file, $file, FTP_BINARY);
// Close connection
ftp_close($conn_id);