KevinT.
KevinT.

Reputation: 372

Detect If PHP is not opened by include

Is there, in any way, possible to detect if a PHP file is browsed by the browser itself and not by include?

I'm using PHP to process some code and then write it in another page in which this PHP is included (using the PHP include()). I don't want it to be browsed by itself and I want it to be accessed only if it is included (again, using the PHP include())

I wanted to achieve something like this:

if (browser is not opened by include){
    header("Location: /forbidden");
    die();
}
else {//do nothing}

Now, is it possible for me to achieve what I want?

Upvotes: 0

Views: 866

Answers (3)

Class
Class

Reputation: 3160

In the order I'd recommend to achieve the desired outcome, first being the best.

Put them in a folder outside the web root.

OR

Create a .htaccess to deny access to the folder except for servers ip.

Options -Indexes
<Files *.php>
Order Deny,Allow
Deny from all
Allow from servers ip
Allow from servers ip if more than one
#Allow from your ip if you want to
</Files>

OR

Create a variable in your parent php file and if it is not set redirect them.

Upvotes: 0

MrMike
MrMike

Reputation: 1540

Looks like you can try the reverse method of this answer:

PHP CHeck if a File is Loaded Directly Instead of Including

Instead of adding the define('APP_RAN') in the "base" file, add it to the include and add the other snippet to the base file.

Upvotes: 1

John Conde
John Conde

Reputation: 219794

Put it outside of your web root. It can't be accessed by web browsers, etc.

An alternative solution is to have a constant declared in your bootstrap or config file (whatever you use) and then check for it in your includes. If it is not present have the include call die().

Upvotes: 2

Related Questions