Redirect safely after a form
Always call exit after a redirect, and never redirect to an address taken straight from the URL (open redirect).
PHP · Redirect safely after a formBeginner
function redirect(string $to): never
{
header('Location: ' . $to, true, 303); // 303 = "see other": the browser switches to GET
exit;
}
// Only allow redirects to pages on your own site
function safe_next(string $next, string $fallback = '/'): string
{
return (preg_match('#^/(?!/)[A-Za-z0-9/_\-.?=&]*$#', $next)) ? $next : $fallback;
}
redirect(safe_next($_GET['next'] ?? '/'));redirectheaderforms