block direct access to php file

Last updated on March 23rd, 2022 at 01:00 pm

If you don’t want users to access some files directly from browser, you can simply add the following php script on top of such files.

Let us take one file named MYFILE.PHP as an example, all you have to do is just add the below code on the header of the script

<?php
// this is first code block
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME']))
{
// tell people trying to access this file directly goodbye...
        exit("This file is restricted from direct access");
}
//Rest of the code in your file comes after this
?>

Hope this is a quick fix for your problem.

We also have a tutorial that talks more about how to prevent direct access to PHP file but the same php file can be called from a different script.

Demo

You might also be interested in,

How to secure PHP script?

One thought on “How to restrict access to php file”

Leave a Reply

Your email address will not be published. Required fields are marked *