How to disable direct access to a file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
techkid
Forum Commoner
Posts: 54
Joined: Sat Sep 05, 2009 11:18 pm
Location: Maldives

How to disable direct access to a file

Post by techkid »

Suppose I've 2 Files. 1.php & 2.php

I don't want anybody to access 2.php directly from browser. Eg: http://localhost/2.php but I want 2.php show up in 1.php like:

Code: Select all

<?php
include("2.php");
?>
My question is how can I disable direct access using php not .htaccess
guosheng1987
Forum Newbie
Posts: 24
Joined: Thu Oct 15, 2009 3:03 am

Re: How to disable direct access to a file

Post by guosheng1987 »

maybe you can wirte code like these

Code: Select all

 
1.php
 
<?php
$a = 5;
include ("2.php");
?>
 
 
2.php
 
 
<?php
if(empty($a))
 redirect...
?>
 
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How to disable direct access to a file

Post by requinix »

If you don't want 2.php accessible from the web then put it in a place that's not accessible from the web.
User avatar
techkid
Forum Commoner
Posts: 54
Joined: Sat Sep 05, 2009 11:18 pm
Location: Maldives

Re: How to disable direct access to a file

Post by techkid »

guosheng1987 wrote:maybe you can wirte code like these

Code: Select all

 
1.php
 
<?php
$a = 5;
include ("2.php");
?>
 
 
2.php
 
 
<?php
if(empty($a))
 redirect...
?>
 
 
Any other possible ways?
Naeem
Forum Commoner
Posts: 31
Joined: Tue Jul 07, 2009 12:48 pm

Re: How to disable direct access to a file

Post by Naeem »

You can also restrict access to your files by doing this:

Code: Select all

 
if (preg_match("/filename.php/", $_SERVER['SCRIPT_FILENAME'])) {
    die("Restricted area get out of here");
    exit;
}
 
change filename.php with your php file name
Hope this help.
Thanks.
Post Reply