PHP check to make sure request is either xmlhttp from my site or normal request from a certain domain
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");
}
}
?>
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.
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).
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 ?
You spelt referrer correctly but unfortunately the person who wrote the HTTP spec couldn't! You need to use HTTP_REFERER
.
You might also want to escape the dot \.
so it only matches a dot and not everything.
Ajax requests are only possible from the same domain. You cannot make an XMLHttp request from another site due to inbuilt security reasons.
This site outlines states perfectly that you cannot launch a cross-domain XMLHTTPRequest http://developer.yahoo.com/javascript/howto-proxy.html
All modern web browsers impose a security restriction on network connections, which includes calls to XMLHttpRequest. This restriction prevents a script or application from making a connection to any web server other than the one the web page originally came from (Internet Explorer will allow cross-domain requests if the option has been enabled in the preferences). If both your web application and the XML data that application uses come directly from the same server, then you do not run into this restriction.
You need to be aware that HTTP headers are easily spoofed so someone could easily telnet and send that HTTP header and access the page. Do not rely upon HTTP REFERER for sensitive data. The only reasonably safe prevention is to use logins.
精彩评论