How can error reporting be utilized effectively in PHP to debug issues related to password validation and session management?
Issue: Error reporting can be utilized effectively in PHP to debug issues related to password validation and session management by enabling error reporting, using try-catch blocks for exception handling, and logging errors to a file for further analysis.
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Password validation example
$password = "password123";
if(strlen($password) < 8){
throw new Exception("Password must be at least 8 characters long.");
}
// Session management example
session_start();
if(!isset($_SESSION['user_id'])){
throw new Exception("User is not logged in.");
}
// Logging errors to a file
set_error_handler(function($errno, $errstr, $errfile, $errline) {
$errorLog = "Error: $errstr in $errfile on line $errline" . PHP_EOL;
file_put_contents('error.log', $errorLog, FILE_APPEND);
});
// Try-catch block for exception handling
try {
// Code that may throw exceptions
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}