How can FTP be utilized in PHP to access files on remote servers?

To access files on remote servers using FTP in PHP, you can utilize the built-in FTP functions provided by PHP. These functions allow you to connect to an FTP server, authenticate, navigate directories, upload and download files, and perform other FTP operations programmatically.

// Connect to FTP server
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);

// Check connection
if (!$conn_id || !$login_result) {
    die('FTP connection failed');
}

// Change directory
ftp_chdir($conn_id, '/path/to/remote/directory');

// Download a file
$file_to_download = 'example.txt';
$local_file = '/local/path/to/save/file.txt';
if (ftp_get($conn_id, $local_file, $file_to_download, FTP_ASCII)) {
    echo "Successfully downloaded $file_to_download\n";
} else {
    echo "Error downloading $file_to_download\n";
}

// Close connection
ftp_close($conn_id);