Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I denied user access script directly in URL

Tags:

jquery

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?

like image 792
kampit Avatar asked Jan 04 '12 17:01

kampit


4 Answers

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.

like image 138
MasterCassim Avatar answered Oct 23 '22 20:10

MasterCassim


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.

like image 3
nopuck4you Avatar answered Oct 23 '22 19:10

nopuck4you


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);
}
like image 2
Fabrizio Calderan Avatar answered Oct 23 '22 20:10

Fabrizio Calderan


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

like image 1
afaf12 Avatar answered Oct 23 '22 19:10

afaf12