How can one optimize the code for uploading files via FTP in PHP to improve performance and reliability?
When uploading files via FTP in PHP, it is important to optimize the code to improve performance and reliability. One way to achieve this is by using passive mode for FTP connections, which can help with firewall and NAT issues. Additionally, setting the FTP transfer mode to binary can ensure that files are uploaded correctly without any data corruption. Finally, handling errors and implementing proper error checking can help improve the reliability of the file upload process.
// Connect to FTP server in passive mode
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$ftp_conn = ftp_connect($ftp_server);
ftp_pasv($ftp_conn, true);
ftp_login($ftp_conn, $ftp_user, $ftp_pass);
// Set transfer mode to binary
ftp_set_option($ftp_conn, FTP_BINARY, true);
// Upload file
$file_path = '/path/to/local/file.txt';
$remote_file = 'file.txt';
if (ftp_put($ftp_conn, $remote_file, $file_path, FTP_BINARY)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
// Close FTP connection
ftp_close($ftp_conn);