What are the recommended methods for error handling and feedback in PHP backup scripts to ensure successful execution and troubleshooting?
Issue: Error handling and feedback in PHP backup scripts are essential to ensure successful execution and troubleshooting. By implementing proper error handling techniques, such as try-catch blocks and logging errors, you can identify and resolve issues quickly. PHP Code Snippet:
// Set error reporting level and display errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Define a function for logging errors
function logError($message) {
$errorLog = fopen('error.log', 'a');
fwrite($errorLog, '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL);
fclose($errorLog);
}
// Example of using try-catch block for error handling
try {
// Your backup script logic here
// If an error occurs, throw an exception
throw new Exception('Backup failed: Unable to connect to database');
} catch (Exception $e) {
// Log the error message
logError($e->getMessage());
// Display a user-friendly error message
echo 'An error occurred: ' . $e->getMessage();
}