0

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.

3
  • Why would you hide the value from the end user? Use a password defined from your cronjob wich is defined in the php script too. And use no security other than sql attack protection for the ajax calls for the value. Commented Jan 25, 2012 at 9:48
  • If the script is returning a value to an Ajax request, the data is already 'out there' for the user to see. Commented Jan 25, 2012 at 9:48
  • we are generating value from this script, which we don't want to get scrapped. Commented Jan 25, 2012 at 9:50

4 Answers 4

4

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");
}
Sign up to request clarification or add additional context in comments.

Comments

0
if (!eregi('cost.php',basename($_SERVER["REQUEST_URI"]))) { die('access denied'); }

1 Comment

@richsage: Yeah right, thanks for mentioning ... just copied the line from an old project. So, use preg_match instead.
0

Use a secret password for the cronjob

if (isset($_REQUEST['cronpw']) && $_REQUEST['cronpw'] == 'supersecret')
{
    // this is the cronjob
}
else
{
    // this not
}

Comments

0

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...');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.