简体   繁体   English

防止通过直接访问发送PHP表单,允许使用AJAX

[英]Prevent PHP form sending with direct access, allow with AJAX

I have a script that fires off a email everytime someone comments on by FaceBook comment box. 我有一个脚本,当有人通过FaceBook评论框发表评论时,该脚本会触发电子邮件。 Fb.event.subscribe triggers a ajax call to mail.php on my server, which fires off a email to my email address to notify of a new comment. Fb.event.subscribe触发对我服务器上的mail.php的ajax调用,这会触发到我的电子邮件地址的电子邮件以通知新评论。 How do i make this more secure and block access to mail.php directly? 我如何使其更安全并直接阻止对mail.php的访问?

        FB.Event.subscribe('comment.create', function (response) {
            var domain = "<?= $_SERVER['SERVER_NAME']; ?>";
            var url = "<?= $currentUrl ?>";
                alert("comment added");

                            var xmlhttp;
                            if (window.XMLHttpRequest)
                              {// code for IE7+, Firefox, Chrome, Opera, Safari
                              xmlhttp=new XMLHttpRequest();
                              }
                            else
                              {// code for IE6, IE5
                              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                              }

                            xmlhttp.open("GET","http://" + domain + "/mail.php?url=" + url,true);
                            xmlhttp.send();

        });


** ---------- here is mail.php -------- **



<?php 
    $to = "MY EMAIL HERE";
    $subject = "New Comment Added";
    $message = "New Comment posted here: " . $_GET['url'] ;
    $from = "MY EMAIL HERE";
    $headers = "From:" . $from;
    //mail($to,$subject,$message,$headers);
    //echo  $_GET['accesstoken'] ;
?>

You cannot do this. 你不可以做这个。 If you enable the client to access mail.php with client-side code, then anyone can access it with a script as well. 如果允许客户端使用客户端代码访问mail.php ,那么任何人都可以使用脚本来访问它。 You can try to obfuscate it as much as you want, but if someone really wants to find out how to access it they will. 您可以尝试根据需要对其进行尽可能多的混淆,但是如果有人真的想找到如何访问它,他们会这样做。

EDIT : The basic rule is, if it can be done in a browser by a human, then it can be done in a script by a computer. 编辑 :基本规则是,如果可以由人在浏览器中完成,则可以由计算机在脚本中完成。 The only semi counter-point to this rule are CAPTCHAs, but even these can be circumvented nowadays. 与此规则唯一的半对立是验证码,但如今即使是这些也可以绕开。

You can add a header check in your php script like this: 您可以在PHP脚本中添加标头检查,如下所示:

<?php
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    //send email
  }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM