header 的 .htaccess 和使用 PHP 的页脚

.htaccess for header and footer using PHP

我知道我可以写

php_value auto_prepend_file "/root-directory/header.php"
php_value auto_append_file "/root-directory/footer.php"

.htaccess 以在每个页面的顶部和末尾包含 headerfooter,但这会使它们均匀 before/after <html><body> 标签。

无论如何都可以,但我知道这不是设置 html 页面的好方法。

虽然我可以 "fix" 通过在其末尾放置 </body></html> 标签来解决 footer 的问题(即使它不是这样的好东西每个源代码都没有关闭标签),我找不到修复 header.

的方法

有没有办法告诉 .htaccessheader 放在 <body> 标签之后,而 footer 放在 </body> 之前?

而不是你的 header.phpfooter.php 文件包含(听起来像)原始 HTML(或嵌入 PHP 的 HTML)你也许可以将此内容分配给变量并在 HTML 页面内使用变量 - 无论您希望内容出现在何处。您可以将此文件命名为 template-variables.php,然后您只需要一个包含在 auto_prepend_file.

中的文件

例如:

php_value auto_prepend_file "/root-directory/template-variables.php"

然后在template-variables.php:

<?php
// Template variables...
// (NB: Using HEREDOC <<< syntax)
$HEADER= <<<EOF
<header>
    <h1>Header goes here</h1>
    <p>More content goes here...</p>
</header>
EOF;

$FOOTER= <<<EOF
<footer>
    <p>Footer content goes here...</p>
    <p>Copyright etc.</p>
</footer>
EOF;

在您的 HTML/PHP 文档中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- PHP: Short echo format -->
    <?=$HEADER?>

    <p>Some more content goes here...</p>

    <?=$FOOTER?>
</body>
</html>

封装你可以使用关联数组来保存你的模板变量,这样你在全局命名空间中只有一个变量。例如:

<?php
// Template variables...
$TEMPLATE_VARIABLES = [];
$TEMPLATE_VARIABLES['HEADER'] = 'Hello world';
:

然后,如果需要,您可以轻松遍历脚本中的所有 "template variables"。