Auto Insert Header Files with PHP

I just upgraded to Mint 1.2. When I installed it, the option of automatically inserting the JavaScript include file came up. I never knew that this could be done, but with a few tricks, here it is.

Add this to the .htaccess file in the root html folder, usually named public_html.

<code>AddType application/x-httpd-php .html .htm .php<br />
php_value auto_prepend_file /home/yourcode.php</code>

In that yourcode.php file, buffer the page output with the ob&#95;start function. Then write your function to be called by ob_start that will replace the &lt;/head&gt; tags with your script. Here is an example (not taken from the source code of Mint).

<code>&amp;lt;?<br />
function replaceHeaders() {<br />
 = &#039;&amp;lt;script scr=&quot;/yourjs.js&quot;&amp;gt;&amp;lt;/script&amp;gt;&#039;;<br />
return str_replace(&#039;&amp;lt;/head&amp;gt;&#039;, .&quot;&amp;lt;/head&amp;gt;&quot;, );<br />
}<br />
ob_start(&quot;replaceHeaders&quot;);<br />
?&amp;gt;</code>

Then you get that script inserted in front of the head tag for every freaking page on your site. Even the html ones that don’t include php pages. Damn I’m smart.

post a comment2 Comments

  1. 1November 27th, 2005Mathias says

    Same goes for appending files à la php_value auto_append_file /foo/bar/append.php. I have been applying this functionality to automatically Gzip every document for as long as I can remember, and it works like a charm.

    prepend.php
    <code>&amp;lt;?php ob_start(&#039;ob_gzhandler&#039;); ?&amp;gt;</code>
    append.php
    <code>&amp;lt;?php ob_flush(); ?&amp;gt;</code>
  2. 2November 27th, 2005Jeff Wheeler says

    Matthias: As far as I know, flushing the file is not necessary, as it’s handled automatically by php.

    I wonder if you could make images work, based off the file url and something like this:

    AddType application/x-httpd-php .*
    php_value auto_prepend_file /home/yourcode.php

    And then detect the filename of the requested file, and set the correct header based on that.

Post a Comment

Name and email are required (website is optional). Basic HTML is enabled.

Your email address is not revealed to anyone.