What are some best practices for handling file transfers between directories in PHP using FTP?
When handling file transfers between directories in PHP using FTP, it is important to ensure proper error handling, secure connections, and efficient transfer methods. One best practice is to use passive mode for FTP connections to avoid firewall issues and ensure compatibility with different server configurations.
// Set up FTP connection
$ftp_server = 'ftp.example.com';
$ftp_username = 'username';
$ftp_password = 'password';
$ftp_connection = ftp_connect($ftp_server);
ftp_login($ftp_connection, $ftp_username, $ftp_password);
// Switch to passive mode
ftp_pasv($ftp_connection, true);
// Transfer file from one directory to another
$source_file = 'source_directory/file.txt';
$destination_file = 'destination_directory/file.txt';
if (ftp_put($ftp_connection, $destination_file, $source_file, FTP_BINARY)) {
echo "File transferred successfully.";
} else {
echo "Error transferring file.";
}
// Close FTP connection
ftp_close($ftp_connection);