JDT |
FREE Downloads |
|
Reusing Code - Working with Include() and Require() |
||||
|
Reusing pieces of HTML code is a common way of making web sites (or web applications) more consistent, reliable, and more manageable. Even a small web site consisting of perhaps 20 or 30 web pages can benefit from reusing code for header and footer sections, for example. If the same header or footer is used across all the pages on the site, it makes sense to put the header and footer code in separate files, and then call those files to insert their contents where required. PHP offers two statements that can be used for inserted the contents of one file inside another: include() and require(). These two statements are virtually identical, with the only real difference being that if require() fails, it gives a fatal error, whereas if include() fails it just gives a warning. For this reason I tend to use the include() statement as it just seems slightly more friendly. So, to include the contents of a file called header.inc inside a web page called index.php, you would just need to insert the following line of code (wrapped in PHP opening and closing tags) inside index.php. include 'header.inc'; As PHP takes no notice of the extension used for the included file, you can use whatever extension you want to. Be careful though, if you put passwords inside an include file with a '.inc' extension, they will be visible. You can get around this by putting include files that contain sensitive information outside the document tree to prevent people from browsing to them. Author: John Dixon Go back to PHP Tutorials home page Go back to Tutorials home page
|