Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a constant for security reason

Tags:

security

php

Some applications use this code as FIRST LINE on every page included by the index.php:

if (!defined('SECURE_CONST')) { die("Access denied!"); }

Why do they need to use this? Is it necessary for security? If yes, how can I use it properly?

like image 684
kuzey beytar Avatar asked Dec 28 '22 12:12

kuzey beytar


2 Answers

It's done to ensure that the files are not executed directly. For example:

/index.php

<?php
  define('SECURE_CONST', 1);
  include 'include_me.php';
?>

/include_me.php

<?php
  if (!defined('SECURE_CONST')) { die("Access denied!"); }
?>

Then, if http://example.com/index.php is requested SECURE_CONST will be defined and so die() will not be invoked when include_me.php is included. However, if http://example.com/include_me.php is requested directly, SECURE_CONST is never defined and so the script bails.

If your web server is configured securely--i.e. files not intended to be accessed directly are outside the web root or in a directory made inaccessible by e.g. .htaccess--this should be unnecessary. Developers who use "security" measures like this probably do so because they assume, rightly, that many people using their software will not take the time to understand the security issues and configure their servers properly, and so use methods like this as a failsafe.

like image 86
Jordan Running Avatar answered Jan 08 '23 22:01

Jordan Running


This is probably meant to protect against directly requesting files that are supposed to be used as included/required files only.

Usually, the constant is defined in, for example, your index.php:

index.php

<?php  
define('SECURE_CONST', true);  
require('someIncludeFile.php');

someIncludeFile.php

<?php
if (!defined('SECURE_CONST')) { die("Access denied!"); }
// the actual code starts here
like image 23
Jacco Avatar answered Jan 08 '23 20:01

Jacco