Hi guys hope you can help me with this. I want to get the "Domain name" of the requesting application from my API. Example:
Requesting url:
http://myrequestor.com/
API /Application URL:
http://myapi.com/request/validate/
Now on my validate function whenever an external application request something from the API URL I would like to retrieve the Domain name of the requesting application. Its something like I would like to know if the domain name requesting for it is among the blacklisted application.
Any idea guys? sorry for the confusing question.
Use $_SERVER["HTTP_REFERER"] - But not always set, can be manipulated, and not reliable. (Same goes for other HTTP headers)
<?php
if (array_key_exists('HTTP_REFERER', $_SERVER)){
//do your validation
if (in_array($_SERVER["HTTP_REFERER"], $myBlacklistDomains)){
//fail
}
}
else{
//fail?
}
?>
You should use php's SERVER function. Have a look at this. PHP SERVER .
You can use HTTP_REFERER in PHP.
The HTTP REFERER in PHP is stored in the $_SERVER super global, and can be referenced from anywhere in your PHP code like in the following example, which would simply write it out to the browser:
<?php
echo $_SERVER['HTTP_REFERER']; //Print the URL address from where user opens your link.
?>
Also check this link for more details : http://www.electrictoolbox.com/php-http-referer-variable/
Related
I'm working on a small Restful API, which will show users current weather conditions in their location in the header of the page. There will be a GET query sent to the server via Ajax to a link similar to this:
https://test.com/weather/{required location}
Test.com represents my link which further queries either the database or external APIs. It responds with JSON and they will see the weather for their location. The problem that I have is if that link is accessed directly, it just prints the output, so potentially it could get farmed.
The question I have is how can I implement some sort of logic where if the the page is accessed via ajax from test.com, the output is JSON as needed. Any other ways to access that link will display a blank or custom page with JSON hidden?
Also, as I am new to API and Ajax work, are there any other security means I need to be aware of?
I'm using jQuery, php and mysql.
Thanks
I just found a partial solution myself, using Dontfeedthecode's idea of utilising $_Server varialbes. The one that is suitable is $_SERVER['HTTP_X_REQUESTED_WITH'].
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
echo 'JSON RESPONSE HERE';
} else {
echo 'ALTERNATIVE PAGE HERE';
}
Found out that when Ajax query is sent with 'X-Requested-With: XMLHttpRequest' header according to this. So if we look for the header, we can find out how to treat it. However, from my understanding this will not prevent potential farming.
I will further investigate Dontfeedthecode's response to see if I can get it to work against farming.
You can check $_SERVER['HTTP_HOST'] against allowed domain names.
Taken from: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?
$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
exit;
}
This may be a duplicate of:
Prevent Direct Access To File Called By ajax Function
when use GET Method for receive JSON data , we can acsses the result directly from web browser , for example i send a mydata value from ajax to a main.php file and it process and get answer show a result some thing like below :
<?php
if (isset($_GET["mydata"])) {
if ($_GET["mydata"]=="hello"){
echo "hello world";
}
}
?>
but when a user call it in browser directly like http:mysite.com/mydata.php?mydata=hello recive answer . i want dont allow users to get answer of http request directly , and just can show it from ajax result of main page is it possible ?
You're asking how to prevent an ajax-only request from being accessed directly by copy-pasting the URL into the web browser; that is, only allowing the URL to be accessible via ajax on the main web page.
Well, there are a few things you can try:
Check the Referrer for the URL of the main page with $_SERVER['HTTP_REFERER']
Set a header in Javascript using xhr.setRequestHeader() and then ensure it's value by checking for $_SERVER['HTTP_X_....'] in PHP
Like Jay Bhatt recommended, check for the X_REQUESTED_WITH header, but be aware this might not always be set (see: X-Requested-With header not set in jquery ajaxForm plugin)
However, in any of these situations you should be aware that anyone who knows what they are doing can easily set any HTTP header, variable, or even modify the referrer which is sent to the server. As such, there is no 100% guarantee that your resouce can be accessed only via AJAX on the main web page. There is no control built in the internet to verify where a request is coming from, so anyone can easily spoof or fake it.
I'm trying to blocked website based proxy's. These are normally in the format of:
http://3.hidemyass.com/ip-8/encoded/Oi8vZ29kbGV5ZGVzaWduLmNvLnVrL0xDcmVkaXJlY3QvZnVuY3Rpb25zL2Z1bmN0aW9
My theory of blocking these is to get the URL of the address bar and check that it's actually direct access to my site, rather than visiting via a website proxy.
However, when i try to visit my site and attempt to capture the url of the user it still reports that its my sites url.. not this web based proxy one.
I've tried the following ways of detecting it:
$url= $_SERVER['HTTP_HOST']; //get the url
$url = $_SERVER["SERVER_NAME"];
any ideas on how to resolve this?
UPDATE
Ok i've rewrote part of this, however it always seems to be returning false... the $url is being passed correct as i can echo this out within the function. However it doesnt seem to be matching and returning false
<script>
var url = window.location.href;
<?php $url = "<script>document.write(url)</script>"; ?>
</script>
<?php
//
function checkURLIsSafe($url){
if(preg_match('/www/',$url)){
echo 'true';
} else {
echo 'false';
}
}
checkURLIsSafe($url);
?>
PHP runs on the server. It can only see the URL that was requested from it.
hidemyass.com will be requesting the normal URL from your server. There is no way to tell what URL the browser requested from hidemyass.com.
Approaches you could take include:
Checking the source ip against a list of known proxies
Using client-side JavaScript to read location.href
You cant do it with PHP only. What you can do is to check window.location.href with javascript, and if it's incorrect, send ajax request to server, which will block IP address.
a website has used a "301 permanent redirect" to my site is there a way i can set code that detects this and displays a page when my website is accessed through this?
Does anyone have any idea about this?
You can get only a referer. I think you will not be able to get the http status code on server which the client gets during last request.
So my answer is NO, you cannot get the 301 status code on your server.
But you can do a little of needed magic with referer variable.
e.g. in PHP you can read this:
$_SERVER['HTTP_REFERER'];
Not much you can do. If you were doing the 301, you could set the referrer to the querystring. But since you're not, you can only grab what the request has given you.
You can try using PHP's $_SERVER['HTTP_REFERER'] to track the source URL from where your visitor comes from. I think it's a bit dodgy though and might not yield the same result in all browsers. Even PHP's documentation says 'it cannot really be trusted'.
Why do you have to use .htaccess for the redirect? You could do something like this:
Site A's index.php:
header("Location: http://siteb.com/?ref=".urlencode('http://sitea.com');
Site B's index.php:
if(isset($_GET['ref']))
{
if($_GET['ref']=='http://sitea.com')
{
// Do something
}
}
Edit:
If you can't edit Site A's code or server settings, try using:
if($_SERVER['HTTP_REFERER']=='http://sitea.com')
{
// Do something
}
one of my php page returns data like this:
<?php
//...
echo "json string";
?>
but someone else use file_get_contents() to get my data and use in other website.
can anybody tell me what can i do to prevent such thing happen.
i consider if i can get the request's domain name to echo something else.but i dont know
the function to get request's domain name.and if the request is sent by a server,that
will be unhelpful. My English is poor, to express doubts, please bear with.
you can also use sessions. if somewhere in your application, before the user gets the json data, you start a session, then in this page where you are outputting json data, you can check for the session variable. this way only users that have passed the session generator page, can view your output.
suppose you have page A.php that generates the session. use this code before outputting anything in this page.
session_start();
$_SESSION['approvedForJson'] = true;
then in your page where you are outputting json data, before outputting anything, call session_start() again. the beginning of your PHP code is a good place to call it.
then before outputting the json data, check if the session variable for approved users exists, or not.
if ( isset($_SESSION['approvedForJson']) && $_SESSION['approvedForJson'] ) {
echo "json data";
} else {
// bad request
}
You can use $_SERVER['REMOTE_ADDR'] to get the address of the client address. You can also check $_SERVER['HTTP_REFERER'] and block external requests that way, but it's less reliable. There's probably a few other techniques involving $_SERVER that you can try.
Your fighting an uphill battle here. I am assuming your serverside process that responds in json is being consumed via javascript in your users browsers... so there is no easy way to encrypt it. You might try some of the techniques used to prevent xspf (see http://en.wikipedia.org/wiki/Cross-site_request_forgery ). If you developed the client to pass along some session token that is uniq per client you could reduce some of the problem. But, chances are whoever is stealing your data is gonna figure out whatever mechanism you put in place ... assuming this is some sort of ajax type thing. If its a server-server thing then as sli mentions, setting up some restrictions based on the remote ip would help, plus setting up some sort of API authentication tokens would help even more (see oauth for some pointers)
You could also using .htaccess with apache block every external request to the page if it get's called internally or block every request that is not from your domain:
Google search thingie
EDIT
You could also use some php file which includes the file which can not be read. So for example you have file.php:
<?php
$allowedFiles[] = 'somefile.php';
$allowedFiles[] = 'someotherFile.php';
$allowedFiles[] = 'jsonReturnFile.php';
if(in_array($_GET['file'], $allowedFiles)){
include( "include/".$_GET['file'] );
}
?>
Then you can allow file_ get _contents() on that file and write a rewriteRule in your .htacces to disallow any request to the include/ folder.
RewriteRule include* - [F,NC]
That will return a 403 forbidden error for a request to that directory or any file in the directory.
Then you can do you JSON request to something like: file.php?file=jsonReturnFile.php&someothherParamReadByJsonFile=1
And when someone tries to get the file contents for the JSON file they will get the forbidden error, and getting the file contents for the include.php won't return anything usefull.