public
Last active

CSRF defense

  • Download Gist
gistfile1.aw
PHP
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
function parseUrl2($url) {
$x = parse_url($url);
if (isset($x['host'])) {
$y = explode(':', $x['host']);
$x['hostname'] = $y[0];
} else {
$x['hostname'] = null;
}
return $x;
}
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$httpHost = parseUrl2('http://' . $_SERVER["HTTP_HOST"]);
$httpOrigin = isset($_SERVER["HTTP_ORIGIN"]) ? parseUrl2($_SERVER["HTTP_ORIGIN"]) : null;
$httpReferer = isset($_SERVER["HTTP_REFERER"]) ? parseUrl2($_SERVER["HTTP_REFERER"]) : null;
if ($httpOrigin != null && $httpOrigin['hostname'] != $httpHost['hostname']) {
header('HTTP/1.1 403 Forbidden');
header("Content-type: text/html; charset=utf-8");
exit("CSRF protection in POST request - detected invalid Origin header: " . htmlspecialchars($_SERVER["HTTP_ORIGIN"]));
}
if ($httpReferer != null && $httpReferer['hostname'] != $httpHost['hostname']) {
header('HTTP/1.1 403 Forbidden');
header("Content-type: text/html; charset=utf-8");
exit("CSRF protection in POST request - detected invalid Referer header: " . htmlspecialchars($_SERVER["HTTP_REFERER"]));
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.