How can error handling be improved in the provided PHP script to better identify and address issues with FTP functions?
The issue with error handling in the provided PHP script is that it lacks proper checks and notifications for FTP function failures. To improve error handling, we can implement try-catch blocks to catch exceptions thrown by FTP functions and display meaningful error messages to identify and address issues more effectively.
<?php
$ftp_server = "ftp.example.com";
$ftp_username = "username";
$ftp_password = "password";
// Connect to FTP server
try {
$ftp_connection = ftp_connect($ftp_server);
if (!$ftp_connection) {
throw new Exception("Failed to connect to FTP server");
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Login to FTP server
try {
$login_result = ftp_login($ftp_connection, $ftp_username, $ftp_password);
if (!$login_result) {
throw new Exception("Failed to login to FTP server");
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Other FTP operations...
// Close FTP connection
ftp_close($ftp_connection);
?>