Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
LoneWolfPR Avatar asked Mar 15 '13 16:03

LoneWolfPR


People also ask

Can AJAX be used with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.

Does AJAX work with local files?

On Desktop, some browsers provide an option to enable ajax access to local files. For Chrome, it's the command line option "--allow-file-access-from-files". For Firefox, it's the config variable security.

Can we use AJAX without URL?

You can either specify the URL or not when sending the AJAX request.


2 Answers

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

like image 106
user3058968 Avatar answered Sep 18 '22 13:09

user3058968


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.

like image 27
cara Avatar answered Sep 20 '22 13:09

cara