仅接受来自特定页面的AJAX $ _GET或$ _POST请求 [英] Only accept AJAX $_GET or $_POST requests from specific page

查看:71
本文介绍了仅接受来自特定页面的AJAX $ _GET或$ _POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检查 $ _ GET $ _ POST 值是从特定页面提交的?

Is it possible to check that the $_GET or $_POST values are submitted from specific page?

例如,在 page1 提交给 page2.php?q = abc 的值中有一个 ajax ,而 page2仅接受从 page1 提交的 q .

For example, there is an ajax in page1 submitted value to page2.php?q=abc, and the page2 only accept the q when it is submitted from page1.

如果我直接浏览到 page2.php?q = abc 页面,除非我从 page1 php 将不会运行.>.

If I directly browse to the page page2.php?q=abc, the php will not run unless I submitted the value from page1.

有可能这样做吗?

因为我可以访问 page2 并获得结果.不要提及 session ,因为我可以验证 session 以满足我的需要,并且提交给php的值是否有效.

Because I can access the page2 and get the result. Don't mention about the session, because I can validate the session to match my needs and the values submitted to php is valid or not.

我要检查的是请求是否从特定页面发送.如果为true,则接受值并进行处理,否则,重定向到主页或其他内容.

What I want is to check if the request is sent from specific page or not. If true, then accept the values and process it, else, redirect to homepage or something else.

我的问题是,不仅要通过Ajax提交值,还要直接访问,例如 href ="page2.php?q = abc" .我想令牌将是最好的方法,查询部分将再次验证.

Edit 2: My question is, not only values submitted through Ajax, but also direct access, such as href="page2.php?q=abc". I guess token will be the best way to do that, and the query part will validate again.

推荐答案

在处理AJAX时可以执行两项安全检查:

There are two security checks you could perform while dealing with AJAX:

if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
       //AJAX Request Detected
}

2)哈希令牌:

在保存AJAX请求的页面上,创建令牌:

2) Hashed tokens:

On the page that's holding the AJAX Request, create a token:

session_start();
$hashed='';
$_SESSION['token'] = microtime(); 
if (defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) {
    $salt = '$2y$11$' . substr(md5(uniqid(mt_rand(), true)), 0, 22);
    $hashed = crypt($_SESSION['token'], $salt);
}

这是将 blowfish 算法与

This is using the blowfish algorithm with the crypt() to create hashed string.

您的AJAX函数如下:

Your AJAX function would be like:

$.ajax({
    type: "POST",
    url: 'page2.php',
    data: {
        action: '<?php echo $hashed;?>', //pasted the hashed string created in PHP
        q: 'test'
    },
    success: function (data) {}
});

由您决定要使用 $ _ GET 还是 $ _ POST 方法.

Upto you whether you want to use $_GET or $_POST method.

然后在接收AJAX请求的第二页上,执行以下操作:

And then on the second page which is receiving the AJAX request, you do:

session_start();
if(crypt($_SESSION['token'], $_POST['action']) == $_POST['action']){
   //Hashed string matches. Request has come from page1.
   echo $_POST['q'];
}

这篇关于仅接受来自特定页面的AJAX $ _GET或$ _POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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