Php script prevent direct access

I use ajax to get the value from php scripts (e.g. cost.php), and I know that it would be easy to access it directly and get that value. I even do cron work on the same script (cost.php), so the cron job will not work if I use the following ...

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  //code here
  die('Invalid Request!');
}

This is a safe way to prevent, and cron jobs will not work if I use the code above so that I can use to provide value from the end user. thank.

0
source share
4 answers

To separate cronjob execution you can use php_sapi_name

Simple use (more reliable, depending on variables on the server side): -

if (php_sapi_name() == "cli") // via cronjob or via cli
{
  die("invalid request");
}

PS: PHP_SAPI , : -

if (PHP_SAPI == "cli")
{
  die("invalid request");
}
+4
if (!eregi('cost.php',basename($_SERVER["REQUEST_URI"]))) { die('access denied'); }
0

cronjob

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

Add this at the top of the code to stop direct access to the script.

if (!defined('BASEPATH')) exit('No direct script access allowed');

If you want to allow AJAX requests,

if (!defined('BASEPATH') &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
exit('You are not allowed here...');
0
source

All Articles