我想在我的web服务器上的每个.php或.html文件中的标签之前或标签之后包含我的PHP文件googleanayltics.php
我想知道:
A)如何在标签之前添加此代码
B)如何在标签之后添加此代码
我想了解这两种方法,以增加灵活性。
我认为可以使用.HTACCESS轻松完成此操作。如果您知道如何实现,或者知道任何更简单的方法,请分享给我。
注:我不想手动进入并在每个文件中输入代码,这就是我提出这个问题的原因(为了节省时间)。
我想在我的web服务器上的每个.php或.html文件中的标签之前或标签之后包含我的PHP文件googleanayltics.php
我想知道:
A)如何在标签之前添加此代码
B)如何在标签之后添加此代码
我想了解这两种方法,以增加灵活性。
我认为可以使用.HTACCESS轻松完成此操作。如果您知道如何实现,或者知道任何更简单的方法,请分享给我。
注:我不想手动进入并在每个文件中输入代码,这就是我提出这个问题的原因(为了节省时间)。
编辑:现在我才看到你实际想要的(由于格式问题而被隐藏)。 虽然有可能,但这将是一件非常笨拙的事情,真的不值得花费这样的努力。 请参阅我的另一个答案以了解如何做到这一点。
有两个php.ini
设置可能会引起你的兴趣:
auto_prepend_file
和 auto_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您可以通过在.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文件中手动设置它们。
在htaccess中,你可以放置以下内容
php_value include_path "your/include/path/here/googleanayltics.php"
如果它在同一个文件夹中
<?php include_once("googleanayltics.php") ?>
<?php include("/customers/f/5/f/example.com/httpd.www/folder/googleanayltics.php"); ?>
以下是你可以做的来实现你想要的功能。
auto_prepend_file
和 auto_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();
?>
这依赖于输出缓冲,相对来说比较昂贵。如果您的脚本也使用了输出缓冲,您可能会遇到问题。
因此,我最好的建议是以一种方式设计您的脚本,使得每个页面都使用一个布局,并且您可以通过更改布局来轻松更改页面中包含的内容。
ob_start
开启输出缓冲,ob_end_flush()
发送缓冲输出并关闭。至于你的另一个问题,我已经更新了我的答案 - 只需切换注释行即可。在 <body>
后插入会更不可靠,因为该标记可能包含属性。 - NullUserException