Allow access to PHP file only through ajax on local server - php

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

Related

Hide var data on ajax

I am making AJAX like function but I have problem that bad user can change the value into any other current user. So, how can I prevent this thing?
$live = 'user1';
$fol = 'user2';
function ajax(like){
var data = 'like='+like+'&CURRENTUSER=<?php echo $live; ?>&TOFOLLOW=<?php echo $fol; ?>';
$.ajax( {
type: 'POST',
url: 'ajax.php',
data: data,
success: function(e) {
$('#success').html(e);
}
});
}
Also I want to move this ajax function into ajax.js file, but i am have problem in getting the value $live and $fol of users because echo $live doesn't work on .js.
So, is there any way to do this like Facebook, Twitter AJAX function does ?
This solution works for apache web-server. For interpreting JS file using php, add this line to your .htaccess file:
AddType application/x-httpd-php .js
And put your script inside ajax.js. One other way is using rewrite URL:
RewriteEngine On
RewriteRule ^ajax.js$ ajax.js.php [L]
And put your scripts inside ajax.js.php file. Of course, all these are if you want to show your URL as JS file.
at the top of your ajax.js or ajax.js.php file, before any kind of output, put this:
header('Content-Type: application/javascript');
I have problem that bad user can change the value into any other current user. So, how can I prevent this thing?
Of course you can not do that at all.
HTTP is a stateless protocol – so each and every request that reaches your server is to be mistrusted, period.
You have to check server-side whether the requesting client is authorized to request/perform whatever action it is he wants to trigger – f.e. by checking that the user id that is passed as the “current” user against the session where you stored your login information. (So when you have the id of the current user stored in there, then there’s no need to actually send it from the client any more in the first place.)
This is one of the most basic security principles of any web application – don’t trust any incoming request, until you have verified that the client has the appropriate authorization. So asking for how to “hide” any data that is send from the client is completely the wrong question – that would be what’s called “security by obscurity”, and that does not work.
There can be many solutions for such problem.
Add one of follow user in session before page load so even you dont need to send data in ajax. Just need to confirm action and all data will be taken from session. Hence hackers cant modify users.(This is how i solved the problem in my project)
You can build an function like encode() & decode(). when you are using data in file encode() it first.Then at code end use decode() to extract the info. Since if invalid data came out mean some one has tempered and you will not execute that action. But you have to create such encode() & decode() yourself.
$live = encode(user1);
At php end
$real_live = decode($live);
3. Ajax request to when start php execution you can have a function like
check_auth(user1,user2);
So even if some one used bad data your security rules can filter them.
Hope you can use any of them.

Prevent user to see directly PHP url in Javascript

I want to prevent user to see directly PHP URL in Javascript.
Example :
{
$.ajax(
{
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}return false;
Is it possible or any way to prevent user see the php URL when He/She view the source of my page ? Sometimes user maybe try to open the php url directly.
Thanks for helps.
I (or any client) can still use any number of tools to figure it out (including the built-in debugger in 99% of the browsers built)--It's not worth obfuscating it.
If you're concerned about direct access, check for an AJAX request in your script. (Still hack-able, but it's a start). As also provided in a previous answer:
<?php
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
if (!$isAjax) die('Unauthorized access');
/* rest of search.php */
As stated in comments,
How can We prevent the User open directly the PHP url ?
You should create a session of very long random string (token) in your php and pass it to the js ajax function, so that it sends the token along with the ajax request. On server side you can check if its the same token generated. You may want to expire the token soon.
I dont know, if its the standard way, but can provide you a start.
Ok to make things clear..
Once its on the client-side(the browser) you can't hide it. Users can still download or view source the client-side return.
Obfuscating is not really needed because you just make things complicated and not protecting anything.
But anything that is server-side code(PHP) will not be shown as it is processed by the server-side and the server just return the results of execution of the server-side code.
well in case of your problem the thing you can do is to check whether the $_POST and $_GET parameters are valid upon reaching your PHP codes thus making every POST and GET request valid and safe. its somewhat like this
<?php
if(isset($_POST['username']) && isset($_POST['password'])){
//everything seems fine
echo 'ok';
}
else{
//someone is doing a direct acess
header('index.php');
}
?>
or check the sessions to protect your pages only for logged-in users
<?php
if(isset($_SESSION['userid'])){
//everything seems fine
echo 'ok';
}
else{
//someone is doing a direct acess
header('index.php');
}
?>

Obtain actual browser URL in PHP

I need to retrieve the actual URL that the user see's in their browser. I have an Ajax request running at page load. Hence, the regular $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"] expression returns the request URL of the Ajax request instead of the actual URL in the browser.
Any idea how to get this?
You could pass it up from javascript in your ajax request, using window.location.href.
Also, it's likely that $_SERVER['HTTP_REFERER'] will contain the browser's current location.
You could also try using $_SERVER['HTTP_REFERER'];. This might work, not 100% sure though.
You can't do that with server-side code, as there is no server-side variable that refers to what the client sees. The only thing you CAN see (and then again, it depends on the browser the user's using, some don't pass this info) is the HTTP_REFERRER variable. This however, is only set when a page calls another, not when users first access your site.
See this for more details.
A possible solution however, might be to use javascript function to send the browser's top URL to the server using an AJAX query, and to fire it client-side whenever a user loads the pages) you want to get this info for.
Edit: Damn, too slow, already answered!
Pass a hidden input that has the browser value set with your ajax request. Unless someone is being malicious, it should suffice.
If you do an Ajax-request, you could pass the address available through Javascripts window.location.href variable as a POST-variable with the request.
With jQuery it would be something like:
$.ajax({
url: 'your-url.php',
type: "POST",
data: { url: window.location.href },
success: function (data) {
// Do something on success
}
});
With such a request you could access the URL on the server-side with a simple:
<?php
$url = $_POST["url"];
?>
Actual Website Link in php
<?php
echo $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>
Server-side languages can't see what happens after they've rendered and outputted the page.

Allow PHP file to be requested by javascript but not directly from browser

I'm using a jquery script that uploads files with ajax and PHP. It sends a request to upload_a_file.php which then uploads files.
Is there a way that I can make sure upload_a_file.php is not loaded directly in a browser?
I tried putting upload_a_file.php above my public_html folder. But can't seem to get javascript to load upload_a_file.php.
Here is the url format I use in the javascript to request upload_a_file.php:
../upload_a_file.php
Is it even possible to access files above public_html with javascript?
JS cannot access anything on a server that you yourself as a user cannot. If a file is outside of the site's document root, it is NOT accessible by a user, or by JS. Imagine the fun place the web would be if JS could magically bypass access restrictions on a server and grab any more. "Aww, I was going to grab this bank's accounts list, but it's not in the document root. Good thing I've got Javascript, it can do everything!"
It'd be like every episode of 24, where "patching into the subnet" can magically bypass any firewall and get data from machines which aren't even online or (better yet) not even powered up. Amazing things, those subnets.
You can check the HTTP header X_REQUESTED_WITH is present and has a value of XMLHttpRequest. This is not non-standard header but most JavaScript frameworks, including jQuery, Prototype, and mootools follow this convention.
In PHP you can access it $_SERVER['HTTP_X_REQUESTED_WITH'];
for example:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// do something
}
The javascript is running in the browser. It makes its requests through the browser. So, No, there's no way to access a page through ajax but not directly from the browser.
No, not directly. You can call other script (PHP or whatever) that will either "call" your script with include or e.g. with fopen or curl.
Nothing can access files above public_html, because the web server will not serve them. Doing so would have obvious security vulnerabilities, like being able to view any file on your filesystem.
If you want to restrict the file to only being able to be loaded via your javascript, I would think you'd want to look at the $_SERVER['HTTP_REFERER'] variable in php. This should be set to the page the javascript is located on when it is being accessed properly. If it is anything else or empty, the user is accessing it in some other manner.
Using this method shouldn't be relied on for security however, because the referer can be spoofed with the right tools.
Since direct browser access to a page is a GET request by PHP, here is a very basic access control method to keep someone from inadvertently going directly to upload_a_file.php:
In your jquery script, use an ajax request with type "POST":
$.ajax({
url: "../upload_a_file.php",
dataType: "json",
type: "POST"
});
and use this in your upload_a_file.php:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// upload a file
} else {
header("Location: http://example.com/myPublicUploadPage.php");
die();
}

access post vars JS or PHP?

I am using jquery to post vars to a php script.
Is it possible to access these vars once the script has posted? If I post the data to the php script, is the only way to access it in the html/js that i posted it from, to send it back from the php script as json?
I cant seem to do it in JS, but even php will not work?, Sorry correction i can access the post vars in the php page, but not in the html/js page i posted from
Any ideas how to access posted vars from the page thats doing the posting?
update: yep to be a bit clearer, i am using a html page with javascript to post to a php page, i would like to access the posted vars in the html javascript page. I tried outputting $.post and $.ajax and these just show a long function.
Cheers
Ke
How are you submitting your elements to php page? If you are doing everything fine and using ajax (see jquery post method) for example, you can access the php variables normally with $_POST['var_name'].
Make sure that:
Your form method type is set to POST
Your ajax request goes successful
You have specified the correct path to your server side script
In PHP, the data should be accessible through the $_POST array, just like if you posted to the script using a form (whether you make an AJAX request or a normal request through your browser, the server behaves the same). If they're not there, perhaps you actually sent your data by GET instead (you could check $_REQUEST, but it's better, and more secure, to know what method your data will be coming in), or else your AJAX request failed.
I don't recommend using $_REQUEST to post something back to your site. If someone changes their $_REQUEST vars on you, then you have an opening for cross site scripting.
Push all your vars to $_SESSION and post them as you see fit but only after they have been purified. That way even if you make some modifications to them after the fact you can rely on the source, which is in the $_SESSION. However if you are trying to perform actions after a page has executed you are straying outside the boundaries of PHP's limitations. People do it all the time with things like Jquery but it doesn't make it right.
Warning: if you allow accessing and process of vars after PHP has finished printing the page, then you run the risk of enabling attacks on your code.
I assume that you are using $.ajax or $.post to do this.
Just keep your data in local variables. There i sno reason why you should lose the posted data, or your php not being able to access it.
If you post code, maybe someone can help better.
In your php function, you can use this:
function foo() {
//do something
echo json_encode($var);
}
I use .ajax, use dataType: "json". The success attribute would be:
$.ajax(
{
url: 'ajaxfile.php',
type: "POST",
data: ($("#myForm").serialize()),
dataType: "json",
success: function(data)
{
//Insert your logic to handle the vars from php
}
});

Categories