How do I denied user access script directly in URL - php

I have a jQuery script using .live() to load it's page content.
$('#content').load("content.php?" + id);
Question: How can I deny a user from accessing the file content.php directly via a URL?
I tried to put this code on top of content.php but Access Denied appear in my #content div
if (!empty($_SERVER['SCRIPT_FILENAME']) && 'content.php' == basename($_SERVER['SCRIPT_FILENAME']))
die('Access Denied');
What is the correct way to make sure users can't access my content.php file using a URL?

You could use some sort of hashing. For example if content.php has the parameter id; you add an additional parameter hash which contains the MD5 hash of "'some random string' + id*15". In content.php you check if the hash & id match; if not access denied.
The computation has to be done in PHP (not ajax) because the user must not know the hashing algprithmus.
With this method the user can look up the source code and access the page directly but you can't disallow that completly because the browser need to access the page to show it. But the user can't access pages he hasn't accessed through ajax before. You could use some headers (HTTP_X_REQUESTED_WITH) to prevent most internet users to access the page directly but experienced users will change the header and access it anyway.

If you want to protect the usage you can use a one time key algorithm. Have the server generate a key that the page will contain in a variable or attribute somewhere. Then on the load command you pass the key to content.php like this:
key = $("{some selector to get the key}")
$('#content').load("content.php?id=" + id + "key=" + key);
Once the page makes the call to server using the key the server will expire the key making it unusable. This way only active page requests will have access to your content.php file.
This method is still not bullet proof but would make it more difficult to access the content.php by the user.

Since you're calling a resource via ajax a possible solution is sending a particular header into the request like HTTP_X_REQUESTED_WITH and then detect the header server side like so:
/* AJAX check */
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
die($content);
}

I suggest reading this: Detecting Ajax Events on the Server.

Is there other content on the mainpage that you could reference from the content.php file to verify that you are loading it as part of the mainpage and not a stand alone page? You could also pass something via a session from the mainpage into the content.php page and then remove the item at the end of loading of the content.php.

If the URL is accessible with AJAX request then it can be accessed directly and there is not much you can do about it. You can try to detect if a request is the AJAX request with:
function isAjaxRequest() {
return array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
and check for it in the beginning of the script:
if (!isAjaxRequest())
die('Access Denied');
but you shouldn't rely on this check too much because it's rather easy to bypass.

Related

Allow access to PHP file only through ajax on local server

I have a website that needs to increment values in a database based upon user interaction. When users click a button a php script is called that increments the value. I'd like to protect this script from being accessed by outside scripts. Currently a user could write their own web page with a javascript function that hits the same php file repeatedly to blow up the value in the database.
Here's my jquery code that does the incrementing:
jQuery(function(){
$('.votebtn').click(function(e){
var mynum = $(this).attr('id').substring(0,5);
$.ajax({
url:"countvote.php",
type:"GET",
data: {
thenum:mynum
},
cache: false,
success:function(data) {
alert('Success!');
}
}
});
});
});
How would I go about making it so that only a call from ajax/jquery on the local server can access 'countvote.php'? If that's not the correct way to go about it, I'm open to any suggestion that will prevent my php script from being abused by outside scripts.
The solution needs two steps.
Firstly the ajax file must allow access only in ajax request with this code.
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}
Secondly the ajax file has access in the name of file that call it with command $_SERVER['HTTP_REFERER'].
So you can restrict access only in the host server.
$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));
if($pos===false)
die('Restricted access');
Maybe the code can work only with the second part
You can check if $_SERVER['HTTP_X_REQUESTED_WITH'] equals xmlhttprequest, but it's not a reliable method to determine whether a request is an AJAX request or not, there is always a way to get around this. But it protects you from random hits like wrongly entered urls, crawlers etc.
Theres not really a 100% method of doing so. AJAX requests are always going to come from a client. Use POST requests instead of GET and that will help deter any issues but not completely stop them and in your php, just drop all get requests.
I am not sure if this will work, but whats about settings an API key on eg. index.php into a $_SESSION variable, afaik this cannot be visible to the user, unless you do it manually, then in the restricted php file, check the $_SESSION['VOTEAPIKEY'] or whatever

Redirect When Using JSON On PHP

I have a ajax form that goes to a php file, i dont want users to be able to directly enter the php file into the URL bar so how would i be able to redirect them if they enter that php file, i cant simply add a header("location:index.html") or the form wouldnt work.
<?php
$Reg['E'] = 'Test';
echo json_encode($Reg);
?>
There's no way to be 100% certain because there's nothing technically special about an ajax request vs. any other request. If you're using jQuery, you can do a check on the X-Requested-With header:
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
...otherwise redirect. You can also put a token in the form such as a random md5 hash and check whether that token is submitted along with the request (compared to a value stored session). This at least requires that the form page be visited first to generate the token, and "normal" users will not be able to get the token.

Is there a way to prevent the post viewed by the visitor?

Supposed the page is example.com/blog/data.php. I am using file_get_contents to get the content in another script page. Now, i want to:
Forbid google search to crawl and index the data.php page.
Forbid the visitor to access it
Is there a way to achieve this?
You can redirect to another page if the request url is example.com/blog/data.php, but a far easier and more logical solution would be to move the file out of your web-root.
Edit: If you really want to keep the file inside the web-root, you can use something like this at the top of the script that you don't want to access directly:
if ($_SERVER['REQUEST_URI'] === $_SERVER['SCRIPT_NAME'])
{
header('Location: /'); // redirect to home page
}
However, this will probably not work in combination with file_get_contents (you need to remove these lines from the result), you could include the file instead.
Don't put data.php under the web root. Keep it in a parallel directory.
You can pass token via GET. Overall your way is slightly wrong. Why don't you incorporate the data.php logic in the script that is calling it.
Simply apply access restriction for authorized users only. You are able to do it in the most simple way by accessing your page using url parama as password:
example.com/blog/data.php?secret=someblah
and in the first of your file data.php do the following:
<?php
if (!isset($_GET['secret']) || $_GET['secret'] != 'someblah')) exit();
?>
However,It is recommended, don't use this from public computer becuase it is not secure but it is the primitive authentication principle.

help with PHP session_destroy();

I have several forms brought in via jQuery .ajax funciton. In the parent page I start a session like this
<php
session_start();
$_SESSION['authenticated'] = 'yes';
?>
then in the form that is loaded have a check like this:
<?php
session_start();
if($_SESSION['authenticated'] != 'yes') {
header("Location: http://www.google.com");
}
?>
I know its not the best, but it's an attempt to stop people form accessing the forms directly. The problem is that if you go to the parent page, then you can enter the form URL and get there because the session was started when you hit the parent page. How can I destroy the session or remedy this issue?
Effectively, you can't.
To make it more complicated, don't request the form URLs directly. Try to request authorize tokens per request of the main page:
If you generate the main page and you know the form to be requested beforehand, then generate tokens e.g. using md5(time().rnd()), associate each with one you your forms and save the association in your session
Then, your JS code won't request the form URLs, but a factory script using a token injected into the JS code
If you find the token in your saved association in your session, emit the form and delete the token in your session.
This way, each form can only be requested once by one preceding call of the main page.
Note, that this isn't fully safe too: If a user requests the URL of the main page using wget, he can request each form once.
You can check $_SERVER['HTTP_REFERER'] in your form .php code to see where the request is coming from. An AJAX call will set the HTTP_REFERER to the page it is called from.
if (strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) === false) {
die();
}
It's not a bulletproof solution. Any page that is publicly accessible can be retrieved by an automated script.

How to end a PHP session on page close

I have several pages inside an AJAX directory. I don't want these pages accessible directly so you cannot just type in the URL of the page within the AJAX directory and access it. I "solved" this by using a PHP session on the page that calls it as follows:
Main page:
<?php
session_start();
$_SESSION['download']='ok';
?>
and on the ajax page I have this:
<?php
session_start();
if($_SESSION['download']!=='ok'){
$redirect='/index.php'; //URL of the page where you want to redirect.
header("Location: $redirect");
exit;}
?>
The only problem is that if a user goes through the correct process once, the cookie is stored and they can now access the page directly. How do I kill the session once they leave the parent page?
thx
why use session ?
if i understood what you want:
<?php /// Is ajax request var ?
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=="xmlhttprequest") {
// do your ajax code
} else {
// redirect user to index.php since we do not allow direct script access, unless its ajax called
$redirect='/index.php'; //URL of the page where you want to redirect.
header("Location: $redirect");
exit();
}
} ?>
A really simple solution is to open up each of the files you want to protect from direct URL entry & add the following to the top:
<?php if (isset($_GET['ajax']) != true) die();?>
Now get rid of your redirect script since it's useless now. You don't need to use sessions for this. Every time you request a page, use it's direct URL, just add ?ajax=1 to the end of it.
By adding the ?ajax=1, PHP will set a key of 'ajax' to the $_GET global variable with the value of 1. If ?ajax=1 is omitted from the URL then PHP will not set a key of 'ajax' in $_GET and thus when you check if it's set with isset() it will return false, thus the script will die and not output anything. Essentially the page will only output data if ?ajax=1 is at the end of the URL.
Someone could still "spoof" the URL and add '?ajax=1' themselves, but that is not the default behavior for people or web browsers. If you absolutely need to prevent this then it will be much more complicated, e.g. using templates outside of a publicly available folder. Most other "simple" solutions will have the same "spoofing" potential.
There's really no way to accomplish this with a 100% certainty - the problem is, both AJAX and regular web browser calls to your web site are using the same underlying protocol: HTTP. If the integrity and security of your site depends on keeping HTTP clients from requesting a specific URL then your design is wrong.
so how do you prevent people from directly accessing files inside certain directories while still letting the site use them??
Create a controller file. Send all AJAX requests to this controller.
ajax-control.php
<?php
$is_ajax = true;
include "ajaxincludes/test.php";
// ... use the ajax classes/functions ...
ajaxincludes/test.php
<?php
if (!isset($is_ajax) || !$is_ajax)) {
exit("Hey you're not AJAX!");
}
// ... continue with internal ajax logic ...
If clients try to access the file directly at http://mysite/ajaxincludes/test.php they'll get the error message. Accessing http://mysite/ajax-control.php will include the desired file.
I don't think there is a surefire way to do what you are asking, since HTTP request headers can be faked. However, you can use $_SERVER['HTTP_REFERER'] to see if the request appears to be coming from another page on your site.
If the rest of the security on your site is good, the failure of this method would not grant the user access to anything they were not already able to access.
I've never tried this but maybe you could do something with jQuery's .unload() and then call a PHP page to unset() the session.
Why not (on Ajax page):
session_start();
if($_SESSION['download']!=='ok'){
$redirect='/index.php'; //URL of the page where you want to redirect.
header("Location: $redirect");
exit;
}
// do whatever you want with "access granted" user
// remove the download flag for this session
unset($_SESSION["download"]);

Categories