Just a quick post today. In this web design tutorial I am going to show you how to use PHP conditional statements and the $_SERVER array to determine what page you are currently viewing. I have seen many websites with duplicate includes just because there is a slight modification to the code on certain pages. The fact is, you don’t have to do this – you can use a simple PHP conditional statement to target specific pages.
Example Header.php
<head> <title>Example Header</title> <?php if ( $_SERVER['REQUEST_URI'] == '/' ) : ?> <script type="text/javascript" src="scripts/script1.js"></script> <?php else : ?> <script type="text/javascript" src="scripts/script2.js"></script> <?php endif; ?> </head>
As you can see in the example above, there is a PHP conditional statement wrapped around the JavaScript. The PHP basically says, if the user is on the home page (which is the root) use script1.js. Any other page, use script2.js.
Another example could be to change text on certain pages. Maybe add a breadcrumb trail to let users know what page they are currently on.
<?php if ( $_SERVER['REQUEST_URI'] == '/' ) : ?> <p>You are currently on the Home Page</p> <?php elseif ( $_SERVER['REQUEST_URI'] == '/about.php' ) : ?> <p>You are currently on the About Page</p> <?php else : ?> <?php //Do Nothing ?> <?php endif; ?>
There is another way you can do this by selecting ‘SCRIPT_FILENAME’ in the $_SERVER array, but I will discuss that next week.