阻止直接访问

时间:2012-11-22 00:48:38

标签: php

如何在不修改.htaccess的情况下阻止直接访问某些页面?

有没有办法通过每个脚本中的一些代码实现这一目标?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:8)

尝试在第一行添加此代码:

根据Michael Berkowski的建议,答案的改进版本将是这样的:

/***************DO NOT ALLOW DIRECT ACCESS************************************/
if ( (strpos( strtolower( $_SERVER[ 'SCRIPT_NAME' ] ), strtolower( basename( __FILE__ ) ) ) ) !== FALSE ) { // NOT FALSE if the script's file name is found in the URL 
  header( 'HTTP/1.0 403 Forbidden' );
  die( '<h2>Direct access to this page is not allowed.</h2>' );
}
/*****************************************************************************/

更新

/***************DO NOT ALLOW DIRECT ACCESS************************************/
if ( stripos( $_SERVER[ 'REQUEST_URI' ], basename( __FILE__ ) ) !== FALSE ) { // TRUE if the script's file name is found in the URL
  header( 'HTTP/1.0 403 Forbidden' );
  die( "<h2>Forbidden! You don't have permission to access this page.</h2>" );
}
/*****************************************************************************/

此代码可用于保护具有其他代码使用的函数,类等的文件,这些代码不需要通过浏览器访问。比如大多数WP插件,admin和include文件,wp-config.php,functions.php;用于获取通过POST方法(非GET)等传输的数据的文件