The Correct Way to Redirect in PHP After Script Completion
There is no goto statement for URLs in PHP. While the concept of jumping to another location is intuitive, web servers do not handle flow control within a script the way an operating system handles process jumps. When you finish a specific task and need to send the user elsewhere, you must explicitly tell the server that the current response is complete and initiate a transfer.
The most reliable method is using the header() function. This approach works because HTTP headers are sent before any body content. If you attempt to use header('Location: $url') after output has already startedâsuch as echoing text, printing HTML, or even sending whitespaceâthe header will fail. PHP throws a fatal error stating that headers cannot be sent when the content is no longer empty.
Here is how the implementation looks in practice:
// SOMETHING DONE
$url = 'https://example.com/thankyou.php';
if (!headers_sent()) {
header('Location: ' . $url, true, 302);
exit();
}
The exit() call is critical here. Once a redirect header is sent, the script continues running by default. Without stopping execution, PHP might attempt to send additional headers or generate output, which corrupts the response or causes unexpected behavior. The third argument in the header() function specifies the HTTP status code. A 302 (Found) indicates a temporary redirect, while 301 (Moved Permanently) tells search engines and browsers that the URL has permanently changed. Choosing between them depends on whether your destination is a permanent replacement or a temporary action, such as returning to a dashboard after a form submission.
Dynamic URLs and Security Considerations
Your request included using a dynamic variable: header('Location: $url'). This pattern is common when handling callbacks or post-action redirects based on user input. However, using variables directly in the header string introduces a significant security risk if not managed correctly. If $url comes from user input, you must validate it against a whitelist of allowed domains.
Constructing a redirect URL with raw user input can lead to Open Redirect vulnerabilities, where an attacker tricks users into visiting malicious sites by exploiting trust in your domain. Always ensure the destination URL is trusted before issuing the header:
$allowedDomains = ['example.com', 'trusted-partner.org'];
if (in_array(parse_url($userInputUrl, PHP_URL_HOST), $allowedDomains)) {
header('Location: ' . $userInputUrl, true, 302);
exit();
}
If the source material for a redirect comes from a database or session rather than direct user input, validation is still advisable to ensure the stored value hasn't been tampered with.
The Laravel Ecosystem Approach
If you are building applications using the Laravel framework, handling redirects is abstracted away into a cleaner syntax. In Laravel, you typically call the redirect() helper function. This method returns an instance of the RedirectResponse class, which can be returned from your controller or route definition.
return redirect()->route('thankyou');
// or with a specific URL
return redirect($url);
Laravel automatically handles the header generation and the necessary exit logic within its response rendering pipeline. This abstraction reduces the chance of accidentally sending output before the redirect, which is a common pitfall in plain PHP scripts. For more complex scenarios involving sessions or flash messages, Laravel provides additional context that plain header() calls cannot easily replicate without manual session management.
Regardless of whether you use raw PHP headers or a framework helper, the fundamental principle remains the same: the current script must terminate immediately after setting the redirect location to ensure a clean HTTP response.
