Top PHP Interview Questions

author image Hirely
at 06 Jan, 2025

Question: How does PHP handle error reporting?

Answer:

PHP provides a robust mechanism for handling errors through error reporting and exception handling. Error reporting determines which types of errors will be displayed or logged during the execution of a PHP script. It also provides developers with the ability to manage how errors are handled and presented to the user.

Here’s a breakdown of how PHP handles error reporting:


1. Error Reporting Levels:

PHP has different error reporting levels that allow you to control what types of errors should be reported. These levels can be configured at runtime using the error_reporting() function or in the php.ini file.

Common error reporting levels include:

  • E_ALL: Reports all errors (except for E_STRICT in older PHP versions).
  • E_ERROR: Fatal run-time errors that stop script execution.
  • E_WARNING: Non-fatal run-time errors (script execution continues).
  • E_NOTICE: Notices that indicate possible problems (e.g., using an undefined variable).
  • E_PARSE: Compile-time parse errors (syntax errors).
  • E_STRICT: Suggests best practices for code compatibility.
  • E_DEPRECATED: Warnings about the usage of deprecated features in PHP.
  • E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE: User-generated errors, warnings, or notices.

Example:

To enable reporting of all errors and warnings, you can use:

error_reporting(E_ALL);

To report only fatal errors:

error_reporting(E_ERROR);

2. Displaying Errors:

To control whether errors are shown to the user, you can use the ini_set() function or modify the php.ini file.

  • display_errors: This directive controls whether errors are displayed as part of the HTML output.

Example:

To show errors in your script:

ini_set('display_errors', 1);  // Show errors

To hide errors (in a production environment):

ini_set('display_errors', 0);  // Hide errors

You can also modify this in the php.ini file:

display_errors = On  // Show errors
display_errors = Off // Hide errors

3. Logging Errors:

PHP can log errors to a file instead of displaying them to the user. This is especially useful in a production environment where you don’t want to expose internal error details to users.

  • log_errors: This directive controls whether PHP logs errors to a file.

Example:

To enable error logging:

ini_set('log_errors', 1);
ini_set('error_log', '/path/to/php-error.log');  // Specify the log file

This configuration writes errors to the specified log file (/path/to/php-error.log).

You can also enable error logging in the php.ini file:

log_errors = On
error_log = /path/to/php-error.log

4. Handling Specific Types of Errors:

PHP allows handling different types of errors and exceptions by using error handlers and exception handlers.

Error Handling:

You can set a custom error handler using the set_error_handler() function. This allows you to define how errors are handled (e.g., logging them, displaying a user-friendly message, etc.).

Example:

function customError($errno, $errstr) {
    echo "Error [$errno]: $errstr";
}

set_error_handler("customError");

echo $undefined_variable;  // This will trigger the custom error handler

Exception Handling:

PHP supports exception handling using try, catch, and throw. This allows you to handle runtime errors more gracefully, instead of using traditional error messages.

Example:

try {
    // Code that may throw an exception
    if (someCondition()) {
        throw new Exception("Something went wrong!");
    }
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

5. Fatal Errors and Shutdown Functions:

  • fatal errors: Errors that stop script execution (e.g., syntax errors, missing function calls). These are not caught by try-catch blocks.
  • register_shutdown_function(): This function allows you to register a shutdown function that will be executed when the script finishes or if a fatal error occurs.

Example:

function shutdownHandler() {
    $error = error_get_last();
    if ($error !== NULL) {
        echo "Fatal error occurred: " . $error['message'];
    }
}

register_shutdown_function('shutdownHandler');

6. Customizing PHP’s Error Reporting via php.ini:

You can configure error reporting globally by modifying the php.ini configuration file. Key directives include:

  • error_reporting: Defines which types of errors should be reported.
  • display_errors: Controls whether errors are displayed in the browser.
  • log_errors: Enables error logging.
  • error_log: Specifies the log file for errors.

Example in php.ini:

error_reporting = E_ALL
display_errors = On
log_errors = On
error_log = /path/to/error.log

7. Suppressing Errors:

You can suppress individual errors by using the @ operator before a function or expression. However, this is generally discouraged because it can hide potential issues.

Example:

$result = @file_get_contents('non_existent_file.txt');

This suppresses any warnings or errors that would otherwise be generated by file_get_contents().


Summary:

PHP provides comprehensive error reporting capabilities that allow developers to manage how errors are displayed, logged, and handled. Key features include:

  • Error reporting levels: Control what types of errors are reported.
  • display_errors: Controls whether errors are shown in the output.
  • log_errors: Enables error logging to a file.
  • Custom error handlers: Set custom error handlers using set_error_handler().
  • Exception handling: Handle runtime errors using try-catch.
  • Fatal errors and shutdown functions: Register a shutdown function to handle fatal errors.

By configuring error reporting appropriately and using exception handling, developers can ensure their PHP applications are more robust, easier to debug, and provide a better user experience.

Question: What is a session in PHP?

Answer:

In PHP, a session is a way to store information (in variables) to be used across multiple pages. Unlike cookies, which are stored on the client-side, session data is stored on the server-side, making it more secure. Sessions are typically used to persist user data (such as login credentials, preferences, or shopping cart information) across different pages and requests.


How Sessions Work:

  1. Session Start:

    • The session is started by calling the session_start() function at the beginning of the script. This function checks if a session already exists and, if not, it creates a new one.
    session_start();
  2. Session Variables:

    • Once a session is started, you can store user-specific data using the $_SESSION superglobal array. This array holds session variables which can be accessed across multiple pages during the same session.

    Example:

    session_start();
    $_SESSION['username'] = 'john_doe';  // Store session data
  3. Accessing Session Variables:

    • You can access stored session data from any page that has called session_start().

    Example:

    session_start();
    echo $_SESSION['username'];  // Output: john_doe
  4. Session ID:

    • Each session is uniquely identified by a session ID. The session ID can be stored in a cookie (PHPSESSID by default), or it can be passed through the URL. The session ID allows the server to associate the session data with a specific user.

    • PHP automatically manages session IDs, but you can access the session ID using session_id().

    Example:

    echo session_id();  // Output: e.g., 6c23e1f4cb846af65db4060a35b438c7
  5. Session Storage:

    • By default, session data is stored on the server in a temporary file. The data is linked to a specific session ID, which is sent to the browser as a cookie.
    • You can customize where PHP stores session data by modifying the session.save_path directive in the php.ini file.

Session Handling Functions:

  1. session_start(): Starts a new session or resumes an existing session.

    session_start();
  2. $_SESSION: An associative array that holds session data. You can read, modify, or delete session variables using this array.

    $_SESSION['user_id'] = 123;
    echo $_SESSION['user_id'];  // Output: 123
  3. session_destroy(): Destroys the session data stored on the server. It does not immediately remove the session variables from the $_SESSION array, but it will prevent access to session data after the script finishes executing.

    session_start();
    session_destroy();  // End the session
  4. session_unset(): Clears all session variables. This is useful if you want to keep the session alive but remove the session data.

    session_start();
    session_unset();  // Removes all session variables
  5. session_regenerate_id(): Generates a new session ID to prevent session fixation attacks. This is commonly used after a successful login to ensure security.

    session_start();
    session_regenerate_id();

Session Lifecycle:

  • Session Creation: A session is created automatically when session_start() is called. PHP generates a unique session ID.

  • Session Variables: You can store information in the $_SESSION array, which is persistent across multiple page requests.

  • Session Expiry: Sessions do not expire automatically unless configured to do so in the php.ini file. You can configure session timeout using session.gc_maxlifetime in the php.ini file, or you can manually expire sessions.

    Example (in php.ini):

    session.gc_maxlifetime = 1440  // 24 minutes
  • Session Destruction: You can explicitly destroy a session using session_destroy() and session_unset() when you no longer need the session data.


Advantages of Sessions:

  1. Server-Side Storage: Since session data is stored on the server, it is more secure than cookies, which can be accessed and modified by the client.
  2. Persistent Data: Sessions can persist data across multiple pages, making it suitable for use cases like user authentication, preferences, or shopping carts.
  3. Session Expiry: Sessions can be configured to expire after a certain period, helping to ensure that sensitive information is not retained indefinitely.

Disadvantages of Sessions:

  1. Server Load: Storing session data on the server can consume resources, especially when handling a large number of sessions.
  2. Session Hijacking: If an attacker steals a session ID, they can impersonate a user. This is mitigated by using secure session management practices, such as HTTPS and session_regenerate_id().

Example of Session Usage (Login System):

// login.php
session_start();

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Assume a simple check
    if ($username == 'admin' && $password == 'password') {
        $_SESSION['user'] = $username;  // Store session data
        header('Location: welcome.php');
        exit();
    } else {
        echo "Invalid credentials";
    }
}
// welcome.php
session_start();

if (isset($_SESSION['user'])) {
    echo "Welcome " . $_SESSION['user'];  // Display the logged-in user
} else {
    echo "You must log in first.";
}
// logout.php
session_start();
session_destroy();  // Destroy the session
header('Location: login.php');
exit();

Summary:

  • A session in PHP is a way to store data across multiple pages or requests. The data is stored on the server and is uniquely identified using a session ID.
  • Sessions are started using session_start(), and session variables are stored in the $_SESSION superglobal array.
  • You can manage sessions by destroying them (session_destroy()), clearing session variables (session_unset()), or regenerating session IDs (session_regenerate_id()).
  • Sessions are commonly used for user authentication, preferences, and other persistent data needs.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as PHP interview questions, PHP interview experiences, and details about various PHP job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now