Disallow direct access to a file in htaccess?

2020-05-08 19:01发布

I would like to disallow users to access directly to a PHP script on my website.

This script should instead be accessed from other scripts on the website.

For example, "somepage.php" can call "upload.php", but users are not allowed to type mywebsite.com/upload.php. Unfortunately I can't move my script to a specific folder.

标签: .htaccess
2条回答
三岁会撩人
2楼-- · 2020-05-08 19:08

As per the comment in my other answer it has become clear that the question actually asked something different. Since i feel that the other answer relates to the question as originally asked, i do not want to edit that one, but rather add this additional answer.

This one will answer: How do i stop a different site from deep linking a page that is being displayed within an iframe on mine?

To do that correctly it is possible to use PHP Sessions. In your main page you would then initiate a session, this user would only be able to view the "inner" page if the session has in fact started.

Let's say you have two pages: index.php and inner.php. You will put the following in the beginning of index.php:

if (session_status() !== PHP_SESSION_ACTIVE) session_start();

In the inner.php you will have:

if (session_status() !== PHP_SESSION_ACTIVE) die("Deep linking detected");

And you definitely cannot do anything like this from htaccess or any other place outside of the code of the pages themselves.

Reference: http://www.php.net/manual/en/function.session-status.php

查看更多
Animai°情兽
3楼-- · 2020-05-08 19:27

Ok, you can do that with the following:

<Files yourfile.inc.php>
  order allow,deny
  deny from all
</Files>

However, i still suggest that you do that from within the PHP, to do that you add to your include file:

if ( !defined( 'YOURPROGRAM' ) )
{
  echo <<<EOT
You cannot display this file
EOT;
  exit( 1 );
}

And then in the files that you wish to have access to this file you would need to do:

define( 'YOURPROGRAM', 1 );

This way your code will be sharable on several platforms, including ngynx, etc.

References: http://htpasswdgenerator.com/apache/htaccess.html and MediaWiki code.

查看更多
登录 后发表回答