典型的方法是在入口点(如 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。因此,在索引中,您将需要一种将请求定向到正确页面的方法。这称为路由。而且是另一个话题...
我尽量保持基本。这真的很简单。
享受。