Application Security

Prevent Open Redirect Vulnerabilities in PHP

Validate redirect destinations so untrusted input cannot send users to attacker-controlled websites.

Overview

A redirect endpoint may accept a next, return or url parameter and send the browser elsewhere. If the destination is not validated, attackers can use a trusted domain to make phishing links look legitimate.

Prefer internal route identifiers

The safest design is to accept a known route key rather than a complete URL. Map that key to a server-defined path. If a full destination is unavoidable, parse it and enforce a strict allow-list.

Reject external destinations by default

Do not rely on checks such as str_contains($url, 'example.com'). Inputs like example.com.attacker.test, user-info syntax and unusual URL forms can bypass naive string checks.

$allowedPaths = [
    'dashboard' => '/account/dashboard',
    'settings'  => '/account/settings',
];

$key = $_GET['return'] ?? 'dashboard';
$destination = $allowedPaths[$key] ?? '/';

header('Location: ' . $destination, true, 303);
exit;

This approach avoids parsing an attacker-controlled absolute URL entirely.

If external destinations are required

Compare the parsed scheme, host and port against a fixed allow-list. Require HTTPS, reject credentials and unexpected ports, and normalize hostnames carefully. Consider internationalized domain names and trailing-dot behavior. A redirect allow-list should be small and maintained centrally.

Preserve safe navigation

For post-login redirects, store a validated local path in the session before authentication, then revalidate it before use. Never assume that a value is safe because it was previously stored in a cookie or hidden form field.

Checklist

  • Prefer route keys mapped to internal paths.
  • Reject protocol-relative URLs and unexpected schemes.
  • Do not use substring checks for host validation.
  • Revalidate redirect targets at the point of use.
  • Use a central redirect helper.
  • Test encoded, malformed and deceptive URL forms.

References

OWASP Unvalidated Redirects and Forwards · PHP parse_url

Share this page Help other developers discover this resource.