What are the best practices for error reporting and handling in PHP scripts to ensure effective debugging and troubleshooting?

To ensure effective debugging and troubleshooting in PHP scripts, it is important to implement proper error reporting and handling techniques. This includes setting error reporting levels, using try-catch blocks for exception handling, logging errors to a file, and displaying user-friendly error messages.

// Set error reporting level
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Use try-catch block for exception handling
try {
    // Your code here
} catch (Exception $e) {
    // Log the error to a file
    error_log($e->getMessage(), 3, "error.log");
    // Display a user-friendly error message
    echo "An error occurred. Please try again later.";
}