Today I am going to continue talking about the $_SERVER[] array. However, instead of selecting ‘REQUEST_URI’ to determine which page the user is on – I will use ‘SCRIPT_FILENAME’.
So lets start by writing the following php code to see what it returns.
<?php echo $_SERVER['SCRIPT_FILENAME']; ?>
Depending on the folder location on the server, it will display something like the below:
/Path/to/directory/index.php
The only bit I am interested in is the actual file name and not path before it. So I am going to use the basename() function to remove the unwanted path.
<?php echo basename($_SERVER['SCRIPT_FILENAME']); ?>
This will display: index.php
This will allow me to target specific pages by using a conditional statement. The below php basically says, if the script name is equal to index.php, display ‘This is the homepage’. Otherwise display ‘This is not the homepage’.
<?php if (basename($_SERVER['SCRIPT_FILENAME']) == 'index.php') : ?> <p>This is the homepage</p> <?php else : ?> <p>This is not the homepage</p> <?php endif; ?>
I could go one step further and remove the .php extension by passing it in as a string. However, this is not essential and is down to you if you wish to do that.
<?php if (basename($_SERVER['SCRIPT_FILENAME'], '.php') == 'index') : ?> <p>This is the homepage</p> <?php else : ?> <p>This is not the homepage</p> <?php endif; ?>
Hope you found this web design tutorial useful.
10:43 24/06/2011
Useful tip about the basename function there, Rob!