Jump to content

[SOLVED] Deny Direct Access to PHP file


Petsmacker

Recommended Posts

Hey there, I need to make it impossible for anyone to load up a PHP page on my site directly in their browser.

It should only be allowed to be 'included' by PHP using the include() function.

It also needs to be picked at by a few AJAX scripts.

 

Is there a secure way of doing this without htaccess scripts? Such as CHMOD?

 

Any help would be appreciated.

Link to comment
Share on other sites

This is easy.

Do this:

includefile.php:

if ($include != 1)
{
exit;
}

//some code that you want to process if the file is included

 

file.php

$include = 1;
include("includefile.php");

Thats it.

You won't be able to run the includefile.php by accessing it directly.

 

You can easily adapt this to check for $_GET values in a URL instead of a variable.

Link to comment
Share on other sites

An easier method is....

 

<?php

  if ($_SERVER['PHP_SELF' == '/' . basename(__FILE__)) {
    exit();
  }

?>

Are you sure? I heard that $_SERVER['PHP_SELF'] can be unreliable.

 

Probably a good point. I don't keep many php files in my web root so don't usually need to worry.

Link to comment
Share on other sites

An easier method is....

 

<?php

  if ($_SERVER['PHP_SELF' == '/' . basename(__FILE__)) {
    exit();
  }

?>

Are you sure? I heard that $_SERVER['PHP_SELF'] can be unreliable.

 

Probably a good point. I don't keep many php files in my web root so don't usually need to worry.

 

What is so un-reliable about that? I use PHP_SELF all the time.

 

 

Or you could do:

 

 

Include("include.php?38383");

 

Then in the include

 

If isset($_GET['38383']){

do script

}else{

die;

}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.