Constants & Superglobals

7 questions found

What is a constant in PHP, and how does it differ from a regular variable?

Beginner
A constant is a named value that, once defined, cannot be changed for the rest of the script's execution, unlike a regular variable whose value can be reassigned at any time, and constants are typically used for values that should remain fixed throughout an application, such as a configuration setting or a mathematical value, making the code clearer about the fact that this value is never expected to change.
define('MAX_LOGIN_ATTEMPTS', 5);
echo MAX_LOGIN_ATTEMPTS;

const APP_VERSION = '1.0.0';
Real-world example A login system defines a constant for the maximum number of allowed failed login attempts, making the value clearly visible and impossible to accidentally overwrite anywhere else in the application's code.

Common follow-ups: What is the difference between using define and the const keyword?;Can a constant's value be an array?

Basics & Types;OOP

What are PHP superglobals, and what are some of the most commonly used ones?

Beginner
Superglobals are built in PHP variables that are always accessible from any scope throughout a script, including inside functions and classes, without needing to explicitly declare them as global, and commonly used superglobals include $_GET and $_POST for accessing submitted form or URL data, $_SESSION for accessing session data, $_SERVER for accessing information about the current request and server environment, and $_FILES for accessing uploaded file information.
echo $_SERVER['REQUEST_METHOD'];
$username = $_POST['username'] ?? '';
Real-world example A login form reads the submitted username and password directly from the $_POST superglobal after the form is submitted, without needing to pass that data through any additional function parameters.

Common follow-ups: Why are superglobals accessible everywhere without needing to be declared global first?;What security precautions should be taken when using data from superglobals like $_GET or $_POST?

Security;Form Handling & Validation

How do you safely retrieve values from superglobals like $_GET or $_POST to avoid undefined index errors and potential security issues?

Intermediate
You should always check whether a specific key exists before accessing it, commonly using the null coalescing operator to provide a safe default value if the key is missing, and you should also validate and sanitize any data coming from these superglobals before using it in your application, since this data originates directly from user input and should never be trusted without verification.
$email = $_POST['email'] ?? '';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo 'Valid email';
}
Real-world example A registration form safely retrieves the submitted email address using the null coalescing operator to avoid an error if the field is missing, and validates it using PHP's built in email filter before processing the registration.

Common follow-ups: What is the null coalescing operator and how does it differ from using isset?;What other PHP filter functions exist for validating different types of user input?

Form Handling & Validation;Security

What is the difference between class constants and global constants, and how do you define and access a constant within a class?

Intermediate
A class constant is defined within a class using the const keyword and is accessed using the scope resolution operator alongside the class name, scoping the constant specifically to that class rather than making it globally available throughout the entire application, which is generally preferred for values that are conceptually tied to a specific class, such as a status code relevant only to an order processing class.
class Order {
    const STATUS_PENDING = 'pending';
    const STATUS_SHIPPED = 'shipped';
}
echo Order::STATUS_PENDING;
Real-world example An order management system defines status related constants directly within the Order class itself, clearly scoping those values to orders specifically rather than polluting the global namespace with generically named constants.

Common follow-ups: Can a class constant's value depend on another constant or a class property?;How do class constants differ from PHP 8.1's readonly properties for representing fixed values?

OOP;PHP 8 Features (Attributes Enums Match Nullsafe Operator)

How does the $_SERVER superglobal provide useful information about the current request and server environment?

Intermediate
The $_SERVER superglobal contains a wide range of information about the current request and the server environment, including the requested URL, the HTTP method used, the client's IP address, and various header values, all of which are commonly used for tasks like routing logic, logging request details, or implementing basic security checks based on the request's origin.
$method = $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['REQUEST_URI'];
$clientIp = $_SERVER['REMOTE_ADDR'];
Real-world example A simple routing system inspects the REQUEST_URI and REQUEST_METHOD values from the $_SERVER superglobal to determine which specific piece of application logic should handle an incoming request.

Common follow-ups: How reliable is the REMOTE_ADDR value for determining a client's true IP address behind a proxy?;What other useful keys are commonly available within the $_SERVER superglobal?

Routing & Middleware;Security

How do enums, introduced in PHP 8.1, provide a more type safe alternative to using class constants for representing a fixed set of related values?

Advanced
Enums let you define a fixed, named set of possible values as a distinct type, providing genuine type safety since a function parameter typed to accept a specific enum can only ever receive one of that enum's defined cases, unlike class constants which are typically just plain strings or integers that could accidentally be replaced with an invalid, unintended value without PHP raising any error at all.
enum OrderStatus {
    case Pending;
    case Shipped;
    case Delivered;
}

function updateStatus(OrderStatus $status) {
    echo $status->name;
}
updateStatus(OrderStatus::Shipped);
Real-world example An order processing system replaces its previous string based status constants with a proper enum, immediately catching a bug at development time where a typo in a status string would previously have silently passed through undetected.

Common follow-ups: What is the difference between a pure enum and a backed enum in PHP?;Can an enum implement an interface or have its own methods?

PHP 8 Features (Attributes Enums Match Nullsafe Operator);Type Declarations & Strict Types

What security risks are associated with directly trusting values from superglobals like $_SERVER, and how should applications guard against header spoofing?

Advanced
Certain values within $_SERVER, such as headers related to the client's claimed IP address behind a proxy, can be manipulated by a malicious client since they ultimately originate from data the client controls, meaning applications should never blindly trust these values for critical security decisions, such as access control, without properly configuring trusted proxy settings and validating that such headers are only accepted from genuinely trusted, known proxy servers.
// Only trust X-Forwarded-For header from known, configured trusted proxies
if (in_array($_SERVER['REMOTE_ADDR'], $trustedProxies)) {
    $realIp = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
}
Real-world example A security audit discovers that an application was using an easily spoofed HTTP header to determine a user's country for pricing purposes, and the team corrects this by only trusting that header when the request genuinely originates from their own known, trusted load balancer.

Common follow-ups: What is the X-Forwarded-For header and why can it be unreliable without proper configuration?;How do popular PHP frameworks handle trusted proxy configuration for this exact problem?

Security;Routing & Middleware