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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With