PHP auto_prepend_file and auto_append_file
This article will show you how to use the PHP configuration directives auto_prepend_file and auto_append_file. These two PHP directives perform the same function as require() but they do it globally on all PHP scripts. The PHP auto_prepend_file and auto_append_file directives can only be used in php.ini files. They do NOT work when used in .htaccess file, I’m mentioning this so that you don’t waste precious time editing your .htaccess file. If you want to set these configuration directives on directory basis you can use them in your custom php.ini file.
The purpose of these PHP configuration directives is to execute a specified file before or after any PHP script stored on your computer/server. This is similar to using a require() function at the beginning or end of a PHP script. The auto_prepend_file directive parses a file before executing any PHP file, so this can be extremely useful if you have a set of user defined PHP functions which need to be called in all PHP scripts.
I’ll explain this scenario, first lets say you’ve created two functions for addition and subtraction.
Save the code in a separate file myfunctions.php. Now edit the php.ini file, this file is located in /etc/php.ini in Linux, C:\PHP\php.ini in Windows, C:\wamp\bin\php\php.ini in WAMP and C:\xampp\php\php.ini in XAMPP. Find and edit the following line
auto_prepend_file = "
/Users/vunamhung/.composer/vendor/autoload.php"
If you’re editing a custom php.ini file you should manually add this line. The location you specify should be an absolute location like /var/www/html/myfunction.php windows users should use forward slash in their file path C:/wamp/www/myfunction.php
Now all you need to do is to call this function in any PHP script you code. The usage of auto_append_file directive is also similar, the only difference is the file specified is parsed AFTER a PHP script executes.
The way in which these configuration directives work might make you think you can use these for adding a header and footer all pages, if you plan to do so remember that while execution the files are merely prepended and appended to the PHP file requested hence you should code in such a way that the header file has the just opening tag for <html>, entire contents of the <head> tag, the opening tag for <body> then the header content. Then the footer file will contain the footer content, closing </body> tag and closing </html> tag in that order. So the main file you code should only have the content that comes after the header contents and before the footer contents. Did you notice how cumbersome it is when used like this ? So it is best you use the auto_prepend_file and auto_append_file directives for including scripts that don’t generate an output viewable on the browser like visitor tracking scripts, user definitions of functions like the example listed above.