Skip to content

Instantly share code, notes, and snippets.

@nczz
Last active October 31, 2015 14:01
Show Gist options
  • Save nczz/dd5722b44a3acdfbae42 to your computer and use it in GitHub Desktop.
Save nczz/dd5722b44a3acdfbae42 to your computer and use it in GitHub Desktop.
PHP - CC Attack Prevention
<?php
$reqMethod = getenv('REQUEST_METHOD');
$reqIP = filter_var(getenv('HTTP_CLIENT_IP'), FILTER_VALIDATE_IP) ? getenv('HTTP_CLIENT_IP') : (filter_var(getenv('HTTP_X_FORWARDED_FOR'), FILTER_VALIDATE_IP) ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR'));
$salt = "Only_U_Know_Me: {$reqIP} in ".round(time() / 604800, 0);
$clientKey = md5($salt);
$expires = gmdate("l, d-M-Y H:i:s T", time() + 604800); // 7 days
if (strtoupper($reqMethod) == 'POST' /*&& EXCLUDE API URL REQUEST*/) {
if (!isset($_COOKIE[$clientKey])){
exit();
}
}
if (strtoupper($reqMethod) == 'GET' && !preg_match('(Google|bing|Yahoo|Baidu|360|Sogou|facebookexternalhit)', getenv('HTTP_USER_AGENT'))) {
if (!isset($_COOKIE[$clientKey])) {
echo '<html><body>
<script type = "text/javascript">
function getCookie(cname) {
var name = " " + cname + "=";
var ca = document.cookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
//while (c.charAt(0) == " ") c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
document.cookie = "'.$clientKey.'=hi; expires='.$expires.'";
if (getCookie("'.$clientKey.'") == "hi") {
window.location.reload();
}
</script></body></html>';
exit();
}
}
echo "{$reqMethod}, {$reqIP}, {$clientKey}";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment