$_SERVER['SCRIPT_FILENAME']

Follow @tristarweb

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.

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..

One Response to $_SERVER['SCRIPT_FILENAME']

  1. Useful tip about the basename function there, Rob!

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