执行你的情况简单deny form all
可能不适合你的要求,所以我提出另一项建议:
相反,你应该随机生成一个散列字符串页面加载,并将其写入到会话:后
session_start();
//$_SERVER['HTTP_X_REQUESTED_WITH'] is pretty much pointless, just illustrating redundancy here, may not work for you so remove as desired
if(isset($_POST['hash_key']) && $_SERVER['HTTP_X_REQUESTED_WITH']):
if(isset($_SESSION['hash_key']) && $_POST['hash_key'] === $_SESSION['hash_key']):
//call your function to process this
return myFunction($_POST['contact']);
else:
//no session key, deny them
header('HTTP/1.0 403 Forbidden');
endif;
elseif(!isset($_POST['hash_key']) && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
//not trying to post, not trying to send ajax, generate a new hash key
$_SESSION['hash_key'] = md5(uniqid(rand(), true));
endif;
现在在页面当生成你的HTML,你需要做一个隐藏的输入携带ŧ他的价值。
<input type="hidden" id="hash_key" name="hash_key" value="<?php echo $_SESSION['hash_key'];?>"/>
现在你可以在你的Ajax函数将该值传递给服务器:
$.ajax({
type: 'POST',
url: 'sendmessage-contact.php',
data: {
'contact' : $("#contact").serialize(),
'hash_key' : $("#hash_key").val()
},
success: function(data){
console.log(data);
}
});
现在,如果机器人尝试垃圾邮件的脚本,它不会不要紧,因为他们将得到禁止403错误,因为它们无法匹配我们为我们的$_SESSION['hash_key']
创建的唯一生成的字符串。
免责声明
请在任何情况下实际使用md5(uniqid(rand(), true))
。我只是简单地提供了这个,它不是一个完全安全的方法。
编辑
过于冗长。简化。
你可以通过客户端(通过JS)调用'sendmessage-contact.php',但是你想从客户端也阻止它?请仔细考虑一下 – HamZa
你不知道你为什么要阻止访问这些文件? –