Reputation: 3716
i have a webpage ... sorto like an api ... basically it prints out some data in form of json .
other website can use this data via php by simply using file_get_contents
or
javascript/jquery ajax request
(jsonp)
anyway i want to be able to black list some unwanted websites , so i have to know where this request are coming from
i've tried
$url = $_SERVER['HTTP_REFERER'];
$domain = parse_url($url, PHP_URL_HOST);
but i get
Undefined index: HTTP_REFERER
so unless i'm mistaken and this was an wierd exception , HTTP_REFERER
doesn't work here .
so how can i get the referee in case of file_get_contents
page request ?
Upvotes: 0
Views: 221
Reputation: 7424
Note that Ajax request are usually sent through the client's browser, while usually a server would call file_get_contents()
or a similar tool, to fetch your page.
So in the case of a server, you can check the REMOTE_ADDR
HTTP header (which contains the caller's IP) against a blacklist.
In the case of an Ajax request, probably from a user agent you can't really say from which website the originated from.
Though I am not sure, but the HTTP_REFERER
header might contain exactly that, but again I have not checked it.
UPDATE (Ajax Requests):
After looking up a little bit, I turn out that browsers don't send referrer data with XHR requests, so you can only blacklist the IPs of the servers you don't want to be accessed from.
Upvotes: 1
Reputation: 71384
HTTP_REFERER is not going to be reliable. You might try $_SERVER['REMOTE_ADDR']
to inspect IP address of remote client.
I would however think that you would have a better time whitelisting approved clients rather then blacklisting, as an attacker could easily proxy a request to get around an IP/host-based blacklist.
There are a number of approaches for whiltelisting:
and so forth.
Upvotes: 0
Reputation: 29424
The HTTP Referrer gets sent by a browser, probably not by file_get_contents()!
You can use $_SERVER['REMOTE_ADDR']
. This will give you the raw IP address from the TCP stack.
In the case of a server-side API call, you get the server's IP (assuming the client does not use any proxies).
However if the client is an AJAX request, you'll get the IP address of the user viewing that page.
Upvotes: 0
Reputation: 143886
Isn't what you're looking for a $_SERVER['REMOTE_ADDR']
? AJAX calls probably won't have a Referer header and that's why you are getting that error.
Upvotes: 0
Reputation: 10033
If the server request it directly then you can use $_SERVER 'REMOTE_ADDR' and 'REMOTE_HOST'.
If they use javascript then you will only get the clients ip. You can use strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') to disallow jquery requests.
Upvotes: 0