Answered by
Oliver Hall
Implementing a 302 redirect in PHP is straightforward and commonly used to redirect users temporarily to a different URL. A 302 status indicates that the resource requested has been temporarily moved to another URI, as indicated by the Location header field.
Basic 302 Redirect
To perform a simple 302 redirect, you can use the header()
function in PHP to modify the HTTP headers sent to the client:
header('Location: http://www.example.com/new-page.php', true, 302); exit(); // Don't forget to call exit() after sending headers
Condition-Based Redirect You might want to redirect users conditionally, for example, based on some business logic or user input:
if ($user->isLoggedIn()) { header('Location: http://www.example.com/dashboard.php', true, 302); } else { header('Location: http://www.example.com/login.php', true, 302); } exit();
Combining with Other Headers Sometimes, additional headers are required before performing a redirect, like setting cookies or handling CORS (Cross-Origin Resource Sharing):
header('Set-Cookie: name=value; expires=Wed, 29-Jun-2024 12:00:00 GMT; path=/'); header('Access-Control-Allow-Origin: *'); header('Location: http://www.example.com/', true, 302); exit();
exit()
After header()
: This prevents the script from running further which could lead to unexpected behavior.By using the above methods, you can effectively manage temporary redirections in your PHP applications.