What are the best practices for handling errors in PHP applications to prevent them from reaching the client on a production system?

When errors occur in PHP applications on a production system, it is important to handle them properly to prevent sensitive information from being exposed to the client. One way to achieve this is by setting the error_reporting level to only display errors in the server logs, while showing a generic error message to the client. Additionally, using try-catch blocks can help catch and handle exceptions gracefully without revealing too much information to the end user.

// Set error reporting level to only log errors
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

// Display a generic error message to the client
function handle_error($message) {
    http_response_code(500);
    echo "An error occurred. Please try again later.";
}

// Example of using try-catch block to handle exceptions
try {
    // Code that may throw an exception
    throw new Exception("An error occurred.");
} catch (Exception $e) {
    handle_error($e->getMessage());
}