-1

A 有一个具有以下结构的分隔“子目录”的网页:

  • 我的网页
    • /subdir/system/ - 这里是 php 表单文件,
  • 索引.php

index.php 调用 /system 中的 file1.php。然后 /system 中的其他文件由“提交”调用。我无法编写正确的.htaccess来防止通过它们的 URL 直接调用这些/system/ 。

我用谷歌搜索并尝试了各种.htaccess内容。但大多数情况下,要么根本无法访问“子目录” (甚至不能从index.php访问),要么是“网页”访问返回了“404”

通常用户应该打开index.php并决定他想要做什么。根据这一点,他被重定向到相应的/system/.php。任何其他尝试/例如添加https://mywebpage/subdir/system/ anyfile。应将他重定向回 index.php 或任何其他“错误页面”。

4

1 回答 1

2

典型的方法是在入口点(如 index.php)中定义一个全局常量,该文件在其他文件之前运行,然后检查每个文件是否定义了该常量

 define('SOME_CONST', true);

然后在每个文件的顶部

if(!defined('SOME_CONST')) die ("No direct access");

因此,在没有首先加载定义常量的文件的情况下访问该文件会导致 PHP 终止。

这个“常量”可以是任何东西,通常我使用相对于 index.php 文件等的基本路径......

    define('MY_BASE_PATH', __DIR__.'/');

等等...

要记住的几件事

我应该提到你不应该在一个文件中定义它并将它包含在你的其他文件中,它不会那样工作。

   //DO NOT DO THIS as IT wont WORK!!!!! - technically it never fails
  //--- in the file somefile.php ---

  //required file defines SOME_CONST
  require 'index.php'; 
  //define('SOME_CONST', true); -- defined in index.php, think of it like copy and pasting that files code at this spot.

  //will never fail, because it's defined by the file included/required above
  if(!defined('SOME_CONST')) die ("No direct access"); 

这就像把它放在你的代码中并期望它失败(显然,它永远不会失败):

  //dont do this either
  define('SOME_CONST', true);
  if(!defined('SOME_CONST')) die ("No direct access"); 

而是这样做:

因此,您必须包含该入口点的文件,并使用诸如路由器之类的东西……基本 MVC。改为这样做(大大简化)

 // --- in index.php ---
define('SOME_CONST', true);

require 'somepage.php';
//if(!defined('SOME_CONST')) die ("No direct access"); included in the above require

接着

//--- in somefile.php ---
if(!defined('SOME_CONST')) die ("No direct access"); //will fail if index.php is not loaded.

因此,如果有人只是说somefile.php未定义常量。因为index.php未在“之前”执行此文件....如果您在检查之前包含index.php(in somefile.php),则不像。您显然不能index.php在检查后包含它 ( )。所以它必须在加载之前somefile.php而不是在somefile.php加载时运行。这就是为什么您不能包含index.phpinsomefile.php而是必须包含somefile.phpin 的原因index.php

显然,您需要的不仅仅是一页somefile.php。因此,在索引中,您将需要一种将请求定向到正确页面的方法。这称为路由。而且是另一个话题...

我尽量保持基本。这真的很简单。

享受。

于 2019-02-16T19:38:46.330 回答