Php 如何通过文件权限禁止特定文件?

Php 如何通过文件权限禁止特定文件?,php,.htaccess,Php,.htaccess,我有一个sendmessage.php文件和其他发送电子邮件的类似文件。我想禁止直接访问这些文件,保持它们的可操作性,但我不知道为什么 如何做到这一点 这就是我使用它们的方式 $.ajax({ type: 'POST', url: 'sendmessage-contact.php', data: $("#contact").serialize(),

我有一个sendmessage.php文件和其他发送电子邮件的类似文件。我想禁止直接访问这些文件,保持它们的可操作性,但我不知道为什么

如何做到这一点

这就是我使用它们的方式

            $.ajax({
                type: 'POST',
                url: 'sendmessage-contact.php',
                data: $("#contact").serialize(),
                success: function(data) {
                    if(data == "true") {
                        $("#send").fadeOut("fast", function(){
                            $(this).before("<p><strong style='color:#D60096'></strong></p>");
                            setTimeout("$.fancybox.close()", 3000);
                        });
                    }
                }
            });
$.ajax({
键入:“POST”,
url:'sendmessage contact.php',
数据:$(“#联系人”).serialize(),
成功:功能(数据){
如果(数据==“真”){
$(“#发送”).fadeOut(“快速”,函数(){
$(此)。在(“”)之前;
setTimeout($.fancybox.close()”,3000);
});
}
}
});

在您的情况下执行简单的
拒绝表单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'];?>"/>
现在,如果僵尸程序试图向您的脚本发送垃圾邮件,那也没关系,因为它们将获得403禁止的错误,因为它们无法匹配我们为
$\u会话['hash\u key']
创建的唯一生成的字符串

免责声明

请在任何情况下都不要实际使用
md5(uniqid(rand(),true))
。我只是为了简洁起见提供了这个方法,它不是一个完全安全的方法

编辑


过于冗长。简化。

您通过客户端(通过JS)调用
sendmessage contact.php
,但您想从客户端阻止它吗?请想一想你不知道为什么要阻止访问这些文件?谢谢你,我正在尝试。但是,我无法获得数据:{}部分工作。如果有帮助的话,我上传了更多的代码。@Karoumpas请查看上面的编辑。
$.ajax({
    type: 'POST',
    url: 'sendmessage-contact.php',
    data: {
        'contact' : $("#contact").serialize(),
        'hash_key' : $("#hash_key").val()
    },
    success: function(data){
        console.log(data);
    }
});