$_SERVER['REQUEST_URI']

Follow @tristarweb

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.

About robert

Hi my name is Rob Hills. At most times you will find me playing around with Magento and Wordpress. I am always looking to improve my web development knowledge – this ranges from PHP, Javascript, jQuery, XML etc. Other than web development – I produce Dance Music. My biggest achievement is getting my track played by Kutski on Radio 1..

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please wrap all source code with [code][/code] tags.

Follow Tristar on Twitter