Current Location: Home> Latest Articles> PHP Backend Redirect Wrapper Tutorial: Efficient Page Redirection

PHP Backend Redirect Wrapper Tutorial: Efficient Page Redirection

gitbox 2025-08-08

Background Introduction

Page redirection is a common requirement in web application development. PHP developers usually use the header function to perform redirects, but it has some limitations and may involve repetitive code. To enhance maintainability and code clarity, it is beneficial to encapsulate the redirection logic.

Encapsulating the Redirect Function

We can create a function named redirect to manage redirection operations consistently.

Function Interface Design

The function supports parameters for the target URL, HTTP status code, and custom headers:

/**
 * Redirect to a specified URL
 * @param string $url Target URL
 * @param int $statusCode HTTP status code, default is 302
 * @param array $headers Custom HTTP headers as key-value pairs
 */
function redirect(string $url, int $statusCode = 302, array $headers = [])

Function Implementation

function redirect(string $url, int $statusCode = 302, array $headers = []) {
    // Set HTTP status code
    http_response_code($statusCode);
    
    // Add custom headers
    foreach ($headers as $name => $value) {
        header("$name: $value");
    }
    
    // Perform the redirect
    header("Location: $url");
    exit;
}

This implementation uses http_response_code to set the status code, header to add custom headers, and then the Location header to redirect, ensuring the script terminates afterward.

How to Use the Encapsulated Function

With this wrapper, calling redirect functions becomes more concise and flexible.

Basic Redirect Example

redirect('https://example.com');

This call will direct users to the https://example.com page.

Using Custom HTTP Status Code

You can specify different status codes to achieve various redirect behaviors, for example, a permanent redirect:

redirect('https://new.example.com', 301);

This call sends a 301 status code indicating a permanent redirect.

Adding Custom HTTP Headers

Custom headers can be passed as the third argument to meet special needs:

redirect('https://example.com', 302, [
    'Referer' => 'https://previous-page.com'
]);

This sets a Referer header before redirecting.

Summary

Encapsulating redirect operations improves code clarity and reusability, allowing flexible control over redirect targets, status codes, and headers. This approach is highly recommended in PHP backend development for efficient and maintainable code.