Reputation: 2824
I am using ajax to get value from php scripts (for example cost.php) and i know it would be easy to access it directly and get that value. I am even running cron job on same script(cost.php) so cron job would not work if i use following...
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//code here
die('Invalid Request!');
}
Is this the safe way to prevent, and cron jobs would not work if i use the above code, so what can i use to secure value from end user. thanks.
Upvotes: 0
Views: 1669
Reputation: 893
Add this at the top of code to stop direct script access.
if (!defined('BASEPATH')) exit('No direct script access allowed');
If you want to allow AJAX requests then,
if (!defined('BASEPATH') &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
exit('You are not allowed here...');
Upvotes: 0
Reputation: 47331
In order to separate execution of cronjob, you can consider to use php_sapi_name
A simple usage (more reliable that depend on server side variables) :-
if (php_sapi_name() == "cli") // via cronjob or via cli
{
die("invalid request");
}
PS: constant PHP_SAPI carry the same value, so you can rewrite to :-
if (PHP_SAPI == "cli")
{
die("invalid request");
}
Upvotes: 4
Reputation: 23563
Use a secret password for the cronjob
if (isset($_REQUEST['cronpw']) && $_REQUEST['cronpw'] == 'supersecret')
{
// this is the cronjob
}
else
{
// this not
}
Upvotes: 0
Reputation: 2947
if (!eregi('cost.php',basename($_SERVER["REQUEST_URI"]))) { die('access denied'); }
Upvotes: 0