PHP Basic Tutorial
MySQL Connection
PHP Advanced
PHP OOP
In PHP, error handling is crucial for building reliable applications. PHP offers several mechanisms to handle errors and exceptions, including both procedural and object-oriented approaches.
This is the preferred modern way (especially for OOP-based code).
try { throw new Exception("Something went wrong!"); } catch (Exception $e) { echo "Caught exception: " . $e->getMessage(); }
Output
Caught exception: Something went wrong!
Custom function for handling non-fatal runtime errors.
function myErrorHandler($errno, $errstr, $errfile, $errline) { echo "Custom Error: [$errno] $errstr in $errfile on line $errline\n"; // Returning true prevents PHP's internal error handler from being triggered return true; } // Set the custom error handler set_error_handler("myErrorHandler"); // Trigger an error echo $undefinedVar; // Notice: Undefined variable
Output
Custom Error: [8] Undefined variable: undefinedVar in /home/dSirIr/prog.php on line 16
Used to handle fatal errors (e.g., syntax or out-of-memory errors) on script shutdown.
function shutdownHandler() { $error = error_get_last(); if ($error !== NULL) { echo "Fatal Error Detected:\n"; echo "Type: {$error['type']}\n"; echo "Message: {$error['message']}\n"; echo "File: {$error['file']}\n"; echo "Line: {$error['line']}\n"; } } register_shutdown_function('shutdownHandler'); // Simulate fatal error undefined_function(); // This causes a fatal error
Output
Fatal Error Detected: Type: 1 Message: Uncaught Error: Call to undefined function undefined_function() in /home/N2ONyS/prog.php:20 Stack trace: #0 {main} thrown File: /home/N2ONyS/prog.php Line: 20
Creating and handling custom exceptions in PHP involves:
1. Defining a custom exception class that extends the built-in Exception class.
2. Throwing the custom exception in your code.
3. Catching it using try/catch.
class MyCustomException extends Exception { // You can customize this class with extra properties/methods if needed }
class MyCustomException extends Exception { // You can customize this class with extra properties/methods if needed } function validateAge($age) { if ($age < 18) { throw new MyCustomException("User must be at least 18 years old."); } return true; }
class MyCustomException extends Exception { // You can customize this class with extra properties/methods if needed } function validateAge($age) { if ($age < 18) { throw new MyCustomException("User must be at least 18 years old."); } return true; } try { validateAge(15); } catch (MyCustomException $e) { echo "Custom Exception Caught: " . $e->getMessage(); } catch (Exception $e) { echo "General Exception: " . $e->getMessage(); }
Output:
PHP Fatal error: Uncaught MyCustomException: User must be at least 18 years old. in
To prevent SQL injection in PHP, the best and most secure approach is to use prepared statements with bound parameters, typically through PDO or MySQLi.
// Connect to the database $pdo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password"); // Prepare statement with placeholders $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email"); // Bind parameter safely $stmt->bindParam(':email', $userInputEmail); // Execute $stmt->execute(); // Fetch results $result = $stmt->fetchAll();
✅ Why this is safe: The input is never directly inserted into the SQL string — it's passed separately and safely.
$conn = new mysqli("localhost", "username", "password", "testdb"); $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?"); $stmt->bind_param("s", $userInputEmail); $stmt->execute(); $result = $stmt->get_result(); The "s" means the parameter is a string.
CSRF is an attack where a malicious website tricks a user's browser into performing unwanted actions on a site where the user is authenticated (e.g. deleting their account).
To prevent this, we use CSRF tokens to verify the legitimacy of requests.
A CSRF token is a unique, random value generated for each session (or form), stored in the session, and verified on every POST request.
// csrf.php session_start(); if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } function getCsrfToken() { return $_SESSION['csrf_token']; }
<?php require_once 'csrf.php'; ?> <form method="post" action="process.php"> <input type="hidden" name="csrf_token" value="<?= getCsrfToken(); ?>"> <input type="text" name="comment" placeholder="Your comment"> <button type="submit">Submit</button> </form>
require_once 'csrf.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) { die("❌ CSRF token validation failed."); } // ✅ Safe to continue $comment = htmlspecialchars($_POST['comment']); echo "✅ Comment received: " . $comment; }
✅ hash_equals() prevents timing attacks.
PHP type hinting (type declarations) means telling PHP what kind of value a function, method, or variable expects.
function add($a, $b) { return $a + $b; }
You could accidentally pass strings or arrays. PHP might throw errors or act strangely.
function add(int $a, int $b): int { return $a + $b; }
✅ This means:
$a → must be an integer
$b → must be an integer
function returns → integer