Correct Code
The correct and safe way to perform HTTP redirects is not to allow the user to directly control the destination URL using unvalidated parameters.
$target = "";
if (array_key_exists("redirect", $_GET) && is_numeric($_GET['redirect'])) {
switch (intval($_GET['redirect'])) {
case 1:
$target = "info.php?id=1";
break;
case 2:
$target = "info.php?id=2";
break;
case 99:
$target = "https://digi.ninja";
break;
}
if ($target != "") {
header("Location: " . $target);
exit;
} else {
?>
Unknown redirect target.
<?php
exit;
}
}
?>
Missing redirect target.
Instead of relying directly on user input, the code implements a fixed list (whitelist) of allowed destinations. This is achieved by using a control structure (switch) that limits the valid values of the redirect parameter to specific, known and previously defined values:
If the received parameter matches any of the valid options (e. g. 1, 2, or 99), a predefined target URL is assigned. Otherwise, no redirection takes place and an explicit error message (Unknown redirect target or Missing redirect target) is displayed. Thanks to this mechanism, even if the user manipulates the redirect parameter trying to redirect to an unauthorized destination, the system will ignore the invalid entry, preventing any malicious attempt of open redirection.
This strict validation technique (whitelisting) is a highly recommended security practice to mitigate Open HTTP Redirect attacks.