Reputation: 123
Currently, I run a PHP function only if GET
requests are sent to the file that it is included in. I send these requests to the PHP file through JavaScript. Also, I want it to ONLY run the function if the get requests are sent through the JavaScript file and is not accessed directly.
For instance:
run.js
function runfun(what, data) {
$.get("files/functions.php",{
run:'true',
what:what,
data:data
},
function(data) {
}
}
functions.php
if (isset($_GET['run']) && isset($_GET['what']) && isset($_GET['data'])) {
runstuff($_GET['what'], $_GET['data']); // I do NOT want this to run if
// the functions.php file is accessed directly and if the GET
// variables are set on the page itself
}
Upvotes: 1
Views: 152
Reputation: 36511
I don't think there is really a bulletproof way of accomplishing this, however, you could use something like the following to detect AJAX requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here */
die($content);
}
Please note this could be spoofed.
Code taken from: http://davidwalsh.name/detect-ajax
Additionally, as @FDL pointed out in their comment, you could use a nonce.
Upvotes: 2