Wednesday, 12 September 2018

Automatically append or prepend files in a PHP script

It is possible with PHP to automatically append or prepend a file to a script using the auto_append_file and auto_prepend_file configuration options. These options can be set in the PHP config, virtualhost settings or in a .htaccess file. This post shows how to set these and how to override a setting so no file is appended or prepended.

Example

As an example of this, if we have three files:
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";
And prepend prepend.php and append append.php using the instructions below, when main.php is called the following would be outputted from the script:
<p>this is the prepended file</p>
<p>this is the main file</p>
<p>this is the appended file</p>

Prepending a script

To prepend a file so it is parsed before the main script, add the following setting to the .htaccess file, php.ini (which of course would affect all websites), or the <virtulahost> config:
php_value auto_prepend_file prepend.php
A path does not need to be included but if it isn't then it will use the include path to find it. This can result in an error like "Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0" if there is no copy of this file in the include path or directory the script is in. So it's best to have the full path to the prepended file.

Appending a script

This is almost the same as prepending a script and the same notes apply. The way to append a file is as follows:
php_value auto_append_file append.php

Overriding a setting so nothing is prepended or appended

If you need to override an existing auto_append_file or auto_prepend_file setting you can do this by setting the value to "none" like so:
php_value auto_prepend_file none
php_value auto_append_file none
This can be useful if you want to have .htaccess set the append/prepend file at the root level of a website but then want a particular subdirectory to not do the append or prepend. You would create a new .htaccess file in that subdirectory which sets them to none as above.

Related posts:

0 comments:

Post a Comment