在 PHP 中检测 Ajax 并确保请求来自我自己的网站

问题描述:

我使用 PHP 后端通过检查 $_SERVER['HTTP_X_REQUESTED_WITH'] 中的值来检测 AJAX 请求.

I use my PHP back-end to detect AJAX requests by checking for a value in $_SERVER['HTTP_X_REQUESTED_WITH'].

这为我提供了可靠的检测,确保使用 AJAX 技术发出请求.

This gives me a reliable detection, making sure the request is made utilizing AJAX techniques.

如何确保请求来自我自己的域,而不是外部域/机器人?

How can I make sure the request came from my own domain, and not an external domain/robot?

www.example.com/ajax?true 可以允许任何人进行 AJAX 调用并切断信息.

www.example.com/ajax?true could allow anyone to make an AJAX call and cut the information.

我可以为正常进入我网站的每个人创建会话,然后允许 AJAX 调用......但这也可以伪造.

I could make sessions for everyone that enters my website normally, and then allow AJAX calls.. but that can be faked too.

这些天还重要吗?

让你控制器

  • 生成访问令牌
  • 存储在会话中以供以后比较

在你的视野中

  • 将访问令牌声明为 JS 变量
  • 随每个请求发送令牌

回到你的控制器

  • 验证 HTTP_X_REQUESTED_WITH
  • 验证令牌

检查这些安全来自 OpenAjax 的指南.
另外,请阅读关于codinghorror.com Annie 链接的文章.

Check these security guidelines from OpenAjax.
Also, read the article on codinghorror.com Annie linked.