PHP
Mitigating Open Redirect Vulnerabilities in PHP
Learn to prevent dangerous open redirect attacks by carefully validating and sanitizing user-provided redirection URLs in PHP applications.
<?php
function is_safe_redirect_url($url) {
// Define allowed hosts for redirection.
// Use an array for multiple allowed domains or a regex pattern.
$allowed_hosts = ['yourdomain.com', 'anotherallowed.com'];
// Parse the URL
$parsed_url = parse_url($url);
// Check if URL is relative (path only) and starts with a slash, implying local path
if (!isset($parsed_url['host']) || empty($parsed_url['host'])) {
return strpos($url, '/') === 0; // Ensures it's a root-relative path
}
// Check if the host is explicitly allowed
return in_array($parsed_url['host'], $allowed_hosts, true);
}
// Example usage:
$redirect_to = $_GET['next'] ?? '/dashboard';
if (is_safe_redirect_url($redirect_to)) {
header('Location: ' . $redirect_to);
exit();
} else {
// Log the attempted malicious redirect
error_log('Attempted open redirect to: ' . $redirect_to);
// Redirect to a default, safe page or show an error
header('Location: /error_page');
exit();
}
?>
How it works: An open redirect vulnerability occurs when an application accepts a user-controlled input that specifies a URL to redirect to and redirects the user to that URL without proper validation. Attackers can exploit this to redirect users to malicious websites, often as part of phishing attacks. This PHP snippet demonstrates how to prevent open redirects by validating the target URL, ensuring it either points to a relative path within the application or an explicitly defined safe host.