如何使用 .htaccess 或其他方法在整个网站中包含一个 PHP 文件

10

我想在我的web服务器上的每个.php或.html文件中的标签之前或标签之后包含我的PHP文件googleanayltics.php

我想知道:

A)如何在标签之前添加此代码
B)如何在标签之后添加此代码

我想了解这两种方法,以增加灵活性。

我认为可以使用.HTACCESS轻松完成此操作。如果您知道如何实现,或者知道任何更简单的方法,请分享给我。

注:我不想手动进入并在每个文件中输入代码,这就是我提出这个问题的原因(为了节省时间)。


谷歌分析通常是一个 JavaScript,如果您的网站正在运行 JavaScript。通常为了性能,我们将 JavaScript 和 CSS 合并到它们自己的单个文件中,并进行压缩/缩小,因此这个 JavaScript 包含已经是整个站点的声明。 - Chris
你有多少个页面?如果你花一次时间使用服务器端的头部和底部包含来处理你的HTML模板(以及Google Analytics),你可以建立一个更加灵活的架构。 - philfreo
5个回答

6

编辑:现在我才看到你实际想要的(由于格式问题而被隐藏)。 虽然有可能,但这将是一件非常笨拙的事情,真的不值得花费这样的努力。 请参阅我的另一个答案以了解如何做到这一点。


有两个php.ini设置可能会引起你的兴趣:

auto_prepend_fileauto_append_file

它们可以通过 .htaccess 进行更改(请参见其他答案)。

注释

  • These will be included before or after the whole PHP script; but not in specific sections of the output.

  • They will only affect files handled that go through PHP, which means HTML files are not included, unless your server is set up to pass HTML files through PHP. This can be done by adding the following line to your .htaccess:

    AddType application/x-httpd-php .html .htm
    
  • Auto prepending a file that generates output is a dangerous thing to do, because it will affect (break) scripts that set headers or use sessions.


为什么是 x-httpd-php?这个值在哪里定义的? - Pacerier

3

您可以通过在.htaccess中设置PHP ini值来附加或预先添加文件。

php_value auto_prepend_file "full_path_to_the_include_directory/prepend.php" 
php_value auto_append_file "full_path_to_the_file_containing_your_analytics_code" 

最好在php.ini文件中手动设置它们。

http://php.net/manual/en/ini.core.php


谢谢,它会将文件添加到哪里?它需要放在</head>标签之前或<body>标签之后。这样行得通吗? - RB. J

1

在htaccess中,你可以放置以下内容

php_value include_path "your/include/path/here/googleanayltics.php"

0

如果它在同一个文件夹中

<?php include_once("googleanayltics.php") ?>

如果不使用这个。
<?php include("/customers/f/5/f/example.com/httpd.www/folder/googleanayltics.php"); ?>

0

以下是你可以做的来实现你想要的功能。

  • 创建两个文件,分别命名为 prepend.phpappend.php
  • 使用之前描述过的方法将它们设置为 auto_prepend_fileauto_append_file

prepend.php

<?php

function callback($buffer) {
    $fileContents = file_get_contents('somefile.html');

    // insert $fileContents right BEFORE </head> tag
    return str_replace('</head>', $fileContents . '</head>', $buffer);

    // insert $fileContents right AFTER <body> tag
    // return str_replace('<body>', . '<body>' . $fileContents , $buffer);

}

ob_start("callback");

?>

append.php

<?php

ob_end_flush();

?>

这依赖于输出缓冲,相对来说比较昂贵。如果您的脚本也使用了输出缓冲,您可能会遇到问题。

因此,我最好的建议是以一种方式设计您的脚本,使得每个页面都使用一个布局,并且您可以通过更改布局来轻松更改页面中包含的内容。


嗨。我不知道输出缓冲是什么,也不知道我的脚本是否使用它……感谢这个 prepend.php 脚本。我该如何修改它来将代码放在特定字符串 "<body"> 之后,并且您能解释一下 ob_start("callback"); 和 ob_end_flush() 是用来做什么的吗?谢谢! - RB. J
@RB.J ob_start 开启输出缓冲,ob_end_flush() 发送缓冲输出并关闭。至于你的另一个问题,我已经更新了我的答案 - 只需切换注释行即可。在 <body> 后插入会更不可靠,因为该标记可能包含属性。 - NullUserException

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接