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.
We can create a function named redirect to manage redirection operations consistently.
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 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.
With this wrapper, calling redirect functions becomes more concise and flexible.
redirect('https://example.com');
This call will direct users to the https://example.com page.
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.
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.
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.