只允许通过本地服务器上的Ajax访问PHP文件 [英] Allow access to PHP file only through ajax on local server

查看:414
本文介绍了只允许通过本地服务器上的Ajax访问PHP文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,需要根据用户交互来增加数据库中的值.当用户单击按钮时,将调用一个php脚本,该脚本会增加该值.我想保护此脚本以防外部脚本访问.当前,用户可以使用javascript函数编写自己的网页,该函数会反复命中相同的php文件,从而炸毁数据库中的值.

I have a website that needs to increment values in a database based upon user interaction. When users click a button a php script is called that increments the value. I'd like to protect this script from being accessed by outside scripts. Currently a user could write their own web page with a javascript function that hits the same php file repeatedly to blow up the value in the database.

这是我的jquery代码,可以进行递增操作:

Here's my jquery code that does the incrementing:

jQuery(function(){
$('.votebtn').click(function(e){
    var mynum = $(this).attr('id').substring(0,5);
    $.ajax({
            url:"countvote.php",
            type:"GET",
            data: { 
                thenum:mynum
            },
            cache: false,
            success:function(data) {
                alert('Success!');
                }
            }
        });
});
});

我将如何实现它,以便只有本地服务器上的ajax/jquery调用才能访问"countvote.php"?如果这不是正确的解决方法,那么我愿意接受任何建议,以防止我的php脚本被外部脚本滥用.

How would I go about making it so that only a call from ajax/jquery on the local server can access 'countvote.php'? If that's not the correct way to go about it, I'm open to any suggestion that will prevent my php script from being abused by outside scripts.

推荐答案

解决方案需要两个步骤.

The solution needs two steps.

首先,使用此代码,ajax文件必须只允许在ajax请求中访问.

Firstly the ajax file must allow access only in ajax request with this code.

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&      strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}

第二,ajax文件可以用命令$ _SERVER ['HTTP_REFERER']调用的文件名进行访问. 因此,您只能在主机服务器中限制访问.

Secondly the ajax file has access in the name of file that call it with command $_SERVER['HTTP_REFERER']. So you can restrict access only in the host server.

$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));
if($pos===false)
  die('Restricted access');

也许代码只能与第二部分一起使用

Maybe the code can work only with the second part

这篇关于只允许通过本地服务器上的Ajax访问PHP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆