PHP Basics: Using php as an extra html tag in dynamic webpages
by , 15th April 2008 at 07:45 AM (1541 Views)
Using includes
When writing a normal pure html page, you quite often have somethings which appear on every page in your site menus, header images etc. Now, what if you want to change one of these things, say you add a new page in and want to add a new link on the menu. In order to do so, you would have to edit every single page on your site to put the new link in. This is very time consuming, not to mention that fact that you may not quite get it the same on every page.
So, what are the solutions?
Many people do this using frames, however I don't think this is the best way to do it also this is a php tutorial so i'm going to ignore this method.
The basis behind the php method is using a simple function, include
This takes another php file and adds its contents into the current file automatically.
Now to add in menus etc we need to create them as a single separate file
this would then be saved as menu.phpHTML Code:<table> <tr><td><b>menu</b></td></tr> <tr><td>url1</td></tr> <tr><td>url2</td></tr> <tr><td>url3</td></tr> <tr><td>url4</td></tr> </table>
the following could also be saved as header.php
and finially footer.phpHTML Code:<html><head><title>my website</title></head> <body> <table> <tr><td><h2>My website</h2></td></tr> </table>
Notice that there is nothing special about these files, they are only fragment of html put into a php file. This means you can just copy and paste your header from your current pages into a new file without any editing at all.HTML Code:<table> <tr><td>Copyright me 2006</td></tr> </table> </body></html>
Then each of your pages would use the following php code:
Notice that the php code we are using is very small, and essentially acts as another html tag in your page. The important part that you need is this:PHP Code:<?php
include('header.php'); //this includes our header
//we close the php tag so we can output normal html?>
<table>
<tr><td><?php include('menu.php');?></td><td>main content for page goes here</td></tr>
</table>
<?php include('footer.php'); ?>
Which you place where you want it to go in the page. Its as easy as adding any other html tag.PHP Code:<?php include('<filename>.php'); ?>
The finial output of this would be:
Dynamically creating each of your pages.HTML Code:<html><head><title>my website</title></head> <body> <table> <tr><td><h2>My website</h2></td></tr> </table> <table> <tr><td><table> <tr><td><b>menu</b></td></tr> <tr><td>url1</td></tr> <tr><td>url2</td></tr> <tr><td>url3</td></tr> <tr><td>url4</td></tr> </table></td><td>main content for page goes here</td></tr> </table> <table> <tr><td>Copyright me 2008</td></tr> </table> </body></html>








