BobbyDouglas
Posts: 5455 Joined: 5/15/2003 From: Arizona Status: offline
|
Neat PHP Include Trick - 1/2/2007 18:22:50
PHP includes are often used to include content that never changes, across many pages. A neat trick with these includes, is to send a variable into the file that is being included, so that you can change information that is being included. Here's an example: When you include your header for the site, in your php page, it looks like this: <?php $page_title="Welcome to my website!"; include("./_includes/header.php"); ?> The header.php file looks like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" >
<head>
<title><?php echo $page_title; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/scripts/address.js"></script>
<?php if($page_title=="Welcome to my website!") { echo
'<script type="text/javascript" src="/scripts/lightbox.js"></script>
<link href="/lightbox.css" rel="stylesheet" type="text/css" />';} ?>
<?php if($page_title=="Welcome to my website! - Login Area") { echo
'<script language="JavaScript" src="/scripts/login.js"></script>';} ?>
</head> This will make sure that the address.js is only loaded on the page that it needs to be loaded on. Javascript isn't always used throughout the entire website, so there isn't a reason to load it in the first place. Another great use would be to use the same header include, except, change the CSS document for certain pages. Another use is for navigation menus: Let's say you have 10 links on your top level for the navigation. When you click on any top level link, there are 3-5 sub links right under it. However, you only want those to display when you click on that specific link. <li><a href="/Some-Place/">Some Place</a><?php if ( $page=="Some-Place" ) {echo '
<ul id="subnavlist">
<li class="first"><a href="#" target="showcase">#</a></li>
<li class="first"><a href="#" target="showcase">#</a></li>
<li class="first"><a href="#" target="showcase">#</a></li>
<li class="first"><a href="#" target="showcase">#</a></li>
</ul>';} ?>
</li>
<li><a href="/Nothing-Under-Here/">Nothing Under Here</a></li>
<li><a href="/Another-Place/">Another Place</a><?php if ( $page=="Another-Place" ) {echo '
<ul id="subnavlist">
<li class="first"><a href="#">#</a></li>
<li class="last"><a href="#">#</a></li>
</ul>';} ?> If Some-Place is within the page title, then it means you are either on that page, or on a sub page of that top page. Because of that, it will display the sub menu under the top menu.
_____________________________
Arizona Web Design - Mr Bobs Web Design in Arizona The Arizona Web Hosting Challenge
|