How can PHP handle errors and exceptions when creating and uploading files to an FTP server?
When creating and uploading files to an FTP server in PHP, errors and exceptions can be handled by using try-catch blocks to catch any exceptions thrown during the process. This allows for graceful error handling and prevents the script from crashing if an issue arises.
<?php
$ftp_server = "ftp.example.com";
$ftp_user = "username";
$ftp_pass = "password";
try {
$conn_id = ftp_connect($ftp_server);
if (!$conn_id) {
throw new Exception("Failed to connect to FTP server");
}
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
if (!$login_result) {
throw new Exception("Failed to login to FTP server");
}
$file = "example.txt";
$remote_file = "/path/to/remote/example.txt";
if (!ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
throw new Exception("Failed to upload file to FTP server");
}
ftp_close($conn_id);
echo "File uploaded successfully!";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>