仅接受来自特定页面的AJAX $

编程入门 行业动态 更新时间:2024-10-10 11:28:59
本文介绍了仅接受来自特定页面的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 .

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 算法与 crypt() 创建哈希字符串.

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 $

本文发布于:2023-10-12 04:23:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483711.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:页面   AJAX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!