How can error handling be improved when copying directories and files to another server in PHP to prevent issues like failed commands or transfers?

When copying directories and files to another server in PHP, error handling can be improved by using try-catch blocks to catch any exceptions that may occur during the transfer process. This allows for more robust error handling and prevents issues like failed commands or transfers.

try {
    // Copy directory and files to another server
    $source = '/path/to/source';
    $destination = 'user@remotehost:/path/to/destination';
    shell_exec("rsync -avz $source $destination");
    
    echo "Files copied successfully!";
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}