PHP检查以确保请求是来自我的站点的xmlhttp还是来自某个域的正常请求 [英] PHP check to make sure request is either xmlhttp from my site or normal request from a certain domain

查看:77
本文介绍了PHP检查以确保请求是来自我的站点的xmlhttp还是来自某个域的正常请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写条件以确保通过xmlhttp请求从我的网站或从允许的外部域访问页面?

How would the condition be written to ensure a page is either accessed by xmlhttp request from my site or from an allowed outside domain?

<?php
    $referrer = $_SERVER['HTTP_REFERER'];
    if($_SERVER["HTTP_X_REQUESTED_WITH"] !== 'XMLHttpRequest') {
        if(preg_match("/accepteddomain.com/",$referrer) {
    header("Location: http://www.domain.com/desiredpage.php");
        } else {
    header("Location: http://www.domain.com/nondesiredpage.php");
        }
    }
?>

推荐答案

考虑到Referer和X-Request-With标头都是由客户端(或不发送)发送的(浏览器或其他任何可以发送HTTP请求的内容),它们将不会受到信任.

Considering that both Referer and X-Request-With headers are sent (or not sent) by the client (the browser, or anything else that can send an HTTP request), they cannot be trusted.

您可以将其用作提示,以增强用户体验;但您不能依靠它们出现或正确.

You can use those as hints, to enhance user-experience ; but you must not rely on them to be either present or correct.

基本上,您无法确保请求来自特定域(即使对于XmlHttpRequest:浏览器也只能在同一域上使用XHR ...但是您无法确保您收到的请求是否来自XHR).

Basically, you have no way to be sure that a request comes from a specific domain (even for XmlHttpRequest : the browser can only use XHR on the same domain... But you have no way to be sure that a request you receive is, or is not, coming from XHR).


(不确定您真正的问题/需求是什么)中,您可能会尝试使用某种API密钥来限制请求率?


Amongst possible ideas (not sure what your real problem / need is), you might try using some kind of API-key, to limit request-rates or so ?

这篇关于PHP检查以确保请求是来自我的站点的xmlhttp还是来自某个域的正常请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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