How can PHP be used to transfer files between servers via FTP, and what are the best practices for ensuring successful transfers?
To transfer files between servers via FTP using PHP, you can utilize the built-in FTP functions provided by PHP. To ensure successful transfers, it is important to handle errors properly, set appropriate permissions, and validate input data to prevent security vulnerabilities.
// Connect to the FTP server
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$ftp_connection = ftp_connect($ftp_server);
ftp_login($ftp_connection, $ftp_user, $ftp_pass);
// Upload a file to the FTP server
$file_to_upload = 'localfile.txt';
$remote_file = 'remotefile.txt';
if (ftp_put($ftp_connection, $remote_file, $file_to_upload, FTP_ASCII)) {
echo "File uploaded successfully";
} else {
echo "Failed to upload file";
}
// Close the FTP connection
ftp_close($ftp_connection);