如果运行 Apache 并且可以访问 .htaccess,您可以执行以下操作,否则请查看@Lock 的答案
prepend.php:
<?php
echo "<p>this is the prepended file</p>\n";
main.php:
<?php
echo "<p>this is the main file</p>\n";
append.php:
<?php
echo "<p>this is the appended file</p>\n";
并使用下面的说明添加 prepend.php 和 append.php,当调用 main.php 时,将从脚本中输出以下内容:
<p>this is the prepended file</p>
<p>this is the main file</p>
<p>this is the appended file</p>
并使用下面的说明添加 prepend.php 和 append.php,当调用 main.php 时,将从脚本中输出以下内容:
<p>this is the prepended file</p>
<p>this is the main file</p>
<p>this is the appended file</p>
预置脚本
要添加一个文件以便在主脚本之前对其进行解析,请将以下设置添加到 .htaccess 文件、php.ini(这当然会影响所有网站)或配置:
php_value auto_prepend_file prepend.php
不需要包含路径,但如果不需要,它将使用包含路径来查找它。如果脚本所在的包含路径或目录中没有此文件的副本,这可能会导致类似“警告:未知:无法打开流:第 0 行的未知中没有此类文件或目录”之类的错误。所以最好获得前置文件的完整路径。
附加脚本
这与添加脚本几乎相同,并且适用相同的注释。追加文件的方式如下:
php_value auto_append_file append.php
覆盖设置,因此没有任何内容被预先或附加
如果您需要覆盖现有的 auto_append_file 或 auto_prepend_file 设置,您可以将值设置为“none”,如下所示:
php_value auto_prepend_file none
php_value auto_append_file none
如果您希望 .htaccess 在网站的根级别设置附加/前置文件,但又希望特定子目录不执行附加或前置操作,这可能很有用。您将在该子目录中创建一个新的 .htaccess 文件,如上所述将它们设置为 none。
来源:http://www.electrictoolbox.com/php-automatically-append-prepend/