您可以尝试以下两种选择:<?php/** * Returns true if current file is included */function isIncluded() { $f = get_included_files(); return $f[0] != __FILE__;}if(!isIncluded()) { // Do some stuff, eg: print some HTML} else { // Show 403/error}?><?php// You can also use (recommended)if(__FILE__ !== $_SERVER["SCRIPT_FILENAME"]) { // this file is being included}?>您也可以选择将文件放入受 a.htaccess和 a保护的目录中,Deny from all因为 PHP 可以绕过它,但用户不能。
在您的 Web 根目录中根本不包含这些脚本是一种常见且最佳的做法。您可以将您的包含放在其他地方的目录中。也就是说,您可能有这样的目录:/www index.php/includes header.php footer.php在你的index.php,你总是可以做require_once('../header.php');这比将您的 Web 服务器配置为禁止访问要好。如果您按照其他人的建议使用.htaccess文件,则该配置可能会丢失、移动、被 webroot 之外的正确配置文件忽略等。您不希望意外泄露这些文件。