PHP Interview Question 4

16.What are different ways to handle errors in PHP?

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.


1. try-catch Block (Exception Handling)

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!

 

2. set_error_handler()

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

 

3. register_shutdown_function()

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

17. How would you create and handle custom exceptions?

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.


1. Define a Custom Exception

class MyCustomException extends Exception {
    // You can customize this class with extra properties/methods if needed
}


2. Use the Custom Exception

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;
}

 

3. Handle with try/catch

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

18 .How do you prevent SQL Injection in PHP?

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.


1. Use Prepared Statements (PDO)

// 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.

 


2. Use Prepared Statements (MySQLi)

$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.

19.Cross-Site Request Forgery (CSRF) Protection

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.


What is a CSRF Token?

A CSRF token is a unique, random value generated for each session (or form), stored in the session, and verified on every POST request.


1. Generate a CSRF Token and Store in Session

// csrf.php
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
function getCsrfToken() {
    return $_SESSION['csrf_token'];
}

 

2. Include the CSRF Token in Your HTML Form

<?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>

 

3. Verify the CSRF Token in process.php

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.


20.waht is php type hinting?

PHP type hinting (type declarations) means telling PHP what kind of value a function, method, or variable expects.


Without type hinting:

function add($a, $b) {
    return $a + $b;
}

You could accidentally pass strings or arrays. PHP might throw errors or act strangely.


With type hinting:

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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.