Preventing Open Redirect Vulnerabilities in PHP
Owner: SnippetBot
Created: 2026-10-16 00:00:24
Size: 2.46 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
function safeRedirect(string $url, array $allowedDomains = []): void
{
// 1. Parse the URL to get its components
$parsedUrl = parse_url($url);
// If the URL cannot be parsed or is malformed, don't redirect
if ($parsedUrl === false || !isset($parsedUrl['host'])) {
header('Location: /error?msg=invalid_redirect_url');
exit();
}
// 2. Normalize and check the host against allowed domains (if provided)
$targetHost = strtolower($parsedUrl['host']);
$currentHost = strtolower($_SERVER['HTTP_HOST'] ?? '');
// Add current host to allowed domains if not already there, assuming internal redirects are fine.
// Or strictly define all allowed domains.
if (!in_array($currentHost, $allowedDomains) && !empty($currentHost)) {
$allowedDomains[] = $currentHost;
}
// 3. If allowedDomains is not empty, check if the target host is in the allowed list
if (!empty($allowedDomains) && !in_array($targetHost, array_map('strtolower', $allowedDomains))) {
// Redirect to a safe default page or an error page
header('Location: /error?msg=unauthorized_redirect');
exit();
}
// 4. Ensure it's an HTTP/HTTPS scheme for security (no data:, javascript: etc.)
if (!isset($parsedUrl['scheme']) || !in_array($parsedUrl['scheme'], ['http', 'https'])) {
header('Location: /error?msg=invalid_scheme');
exit();
}
// All checks passed, perform the redirect
header('Location: ' . $url);
exit();
}
// --- Usage Example ---
// Define your allowed domains (e.g., your own application domains)
$validDomains = ['example.com', 'www.example.com', 'sub.example.com'];
// Example 1: Safe internal redirect
$internalUrl = '/dashboard';
safeRedirect($internalUrl, $validDomains);
// Example 2: Safe external redirect to an allowed domain
// $externalAllowedUrl = 'https://www.example.com/products';
// safeRedirect($externalAllowedUrl, $validDomains);
// Example 3: Attempted redirect to an unauthorized domain (will be blocked)
// $maliciousUrl = 'https://malicious.com/phish?token=user_token';
// safeRedirect($maliciousUrl, $validDomains);
// Example 4: Attempted redirect with javascript scheme (will be blocked)
// $jsInjectionUrl = 'javascript:alert(\'XSS\')';
// safeRedirect($jsInjectionUrl, $validDomains);
// Example 5: Redirect to an internal path (no host in URL means current host is assumed)
// $relativePath = '/settings';
// safeRedirect($relativePath, $validDomains);
?>