Sometime you might face a saturation with you do not want a user to browser/call your PHP file.  In that case obviously you need some kind of protection.  Just use this below code to protect your PHP file from direct call.  Put this at the top of your PHP file which you would like it to be protected from direct call/browse.

 if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { die('You are not allowed to call this page directly.'); }
 

One thought on “Protect Your PHP File From Direct Call

  1. Please note that on case-insensitive operating systems, this check is insufficient!

    On those case-insenstive OS you could trick PHP into allowing the script to be processed just by changing the case of the URL, i.e. from admin.php to admiN.php. The regex wouldn’t match and the site would go through.

    To solve this, you should add an “i” add the end of the regex ( after the last # ), making the regex case-insensitive.

    On unix systems, this could get you into problems again when calling indeX.php from a page called index.php, since the regex would match (false positive) and disallow script execution. You probably wouldn’t have those filenames, though.

    Reply

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>