Thursday, 20 December 2012

Episode 14: Using Includes for Efficient Code



Are you getting sick of typing the same things over and over again? The makers of PHP have blessed us frustrated developers with a little time-saving device called “includes” that save you from reentering frequently used text over and over. Suppose that you want to type the same message on every page of your site. Perhaps it is your company’s
name and address, or maybe today’s date. If you are coding each page of your site from scratch, this is not very efficient for a couple of reasons:

You are typing the same information over and over again, which is never good.
In the case of an update or a change, you have to make the change in every single page of your site. Again, this is redundant and time consuming, and it elevates the potential for human error.

A solution to this problem is to use an include. Includes are PHP files tucked into other PHP files. You take commonly used information and put it in a separate file. For example, if you have a set of defined variables that need to be referenced in every page on your site, you could define them once, in a single PHP script. Then, on each of your pages where you want the variables to appear, you use an include statement that specifies the file that defines the variables. When your script is parsed, the parser inserts the code from the include file into your page, just as if you’d typed it there yourself. The final output is then sent to the browser. Includes can use any extension, but are sometimes referenced as .inc files. If you are adding potentially sensitive information, for example, server variables such as passwords, then it is advisable to save these in .php files so they are never accessible to anyone because the information is parsed before it is sent to the browser. You can add an include in any other file, and if you place the include statement in an if statement, you can control when the include is inserted.

Try It Out Adding a Welcome Message

Suppose you want every page in the movie review site to show a welcome message and perhaps today’s date. You want to create a file that includes this information, so follow these steps:

1. Open your text editor and type the following:
<div align=”center”><font size=”4”>Welcome to my movie review site!</font>
<br>
<?php
echo “Today is “;
echo date(“F d”);
echo “, “;
echo date(“Y”);
?>
</div>
2. Save this file as header.php.
3. To include this file in the three existing movie Web site files, add the following line immediately after the <body> tag to login.php :

<?php include “header.php”; ?>

4. Save your files.
5. Take a look at the files again. If you open login.php  and You will see the same two lines on every page where you have included the header.php file.

Written by “Shojib”.

No comments:

Post a Comment