如何验证对PHP文件的AJAX请求? [英] How to authenticate an AJAX request to a PHP file?

查看:58
本文介绍了如何验证对PHP文件的AJAX请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站上,我有一个注册页面,该页面发出一个AJAX请求,以检查用户名输入后是否可用。此文件名为check.php,与registration.php文件位于同一目录中。当数据发布到check.php时,它将在MySQL数据库中执行查询并返回它使用该用户名找到的用户数。

On my website I have a registration page which makes an AJAX request to check if a username is available after it has been entered. This file is called check.php and is in the same directory as the registration.php file. When data is posted to check.php it will perform a query at a MySQL database and return how many users it found with that username.

如果有人要将数据发布到check.php文件,他们也会看到结果。我需要以某种方式停止这一点,我已经阅读了几个答案,我需要验证每个请求。这可能是一个非常大的话题,虽然我不太清楚要搜索什么来找到它的更多信息。验证每个请求是否是阻止不必要的用户名检查的好方法?如果有的话,如果有人能指出我如何做到这一点,我会非常感激。

If anybody were to post data to the check.php file they would see the result, too. I need to stop this somehow, I've read on a few answers I need to "authenticate" each request. This is probably a very large topic although I'm not too sure what to search for to find more about it. Is authenticating each request a good way to stop unnecessary username checks? If so I would really appreciate it if anyone could point me in the right direction as to how to do this.

推荐答案

答案常见情况:没有 - 你无法阻止这种情况,因为AJAX只是一个HTTP请求。无论您如何保护您的服务器,都可以发送它。因此,如果重点是 - 保护免受'邪恶的黑客'的攻击 - 那么就没有办法做到这一点。正确的是检查/验证服务器端的任何内容。

Answer for common case: no - you can't prevent this, since AJAX is just an HTTP-request. It can be sent no matter how you'll protect your server. So if the point is - to protect from 'evil hackers' - there's no way to do this. The correct though is to check/validate anything on server side.

但这只是基本检查,你可以阅读

But is it's about only basic check, you can read

if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest')

- 但请注意 - 这也是来自客户端的数据,即它不可信(实际上,它只是HTTP请求标头,没有更多)

-but be aware - this is also a data, which came from client i.e. it can't be trusted (actually, it's just HTTP-request header, nothing more)

这篇关于如何验证对PHP文件的AJAX请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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