Finding The Current File Or Directory With PHP

15th May 2008 - 3 minutes read time

Having a header file that prints out a standard menu on a site is a good idea and saves you time in the long run as you only have to edit one file to change an item on the menu. However, what if you only want to display a menu or sub-menu when a particular page is loaded? This is a common problem, and finding out what page you are on is something that all PHP programmer come across at some point or another.

The PHP $_SERVER superglobal array has three items of interest which can be used to find out the current page. These are PHP_SELF,REQUEST_URI and SCRIPT_NAME and they all appear to have the same values but there are some subtle and important differences. Here are some examples of their values (on the right) with the original URL (on the left).

PHP_SELF

test.php = test.php
/example/ = /example/index.php
/example/test.php = /example/test.php
/example/test.php?id=123 = /example/test.php
/example/test.php/test/123 = /example/test.php/test/123

REQUEST_URI

test.php = test.php
/example/ = /example/
/example/test.php = /example/test.php
/example/test.php?id=123 = /example/test.php?id=123
/example/test.php/test/123 = /example/test.php/test/123

SCRIPT_NAME

test.php = test.php
/example/ = /example/index.php
/example/test.php = /example/test.php
/example/test.php?id=123 = /example/test.php
/example/test.php/test/123 = /example/test.php

So from these tests we can say that SCRIPT_NAME is probably our best bet for getting the filename that is running the code we are looking at. We can get that output like this.

$currentFile = $_SERVER["SCRIPT_NAME"];

Next, you will need to extract the parts of the path into an array and pick out the last item. This will be the filename.

$currentFile = $_SERVER["SCRIPT_NAME"];
$parts = explode('/', $currentFile);
$filename = $parts[count($parts) - 1];

I have seem some variations on this theme, but using SCRIPT_NAME seems to be the most reliable method. One thing to watch out for is that one some server setups you might find that SCRIPT_NAME simply doesn't exist. In this case I would use PHP_SELF as this is implemented by the language and will always be present.

To find the current directory you only need to look at the rest of the array. So if the file we are looking at has the following URL.

http://www.hashbangcode.com/blog/example/test/123/test.php

Then our array contained in the $parts variable will contain the following.

[0] => 
[1] => blog
[2] => example
[3] => test
[4] => 123
[5] => test.php

The first item is always blank because the SCRIPT_NAME variable always starts with a slash. So when we use the explode() function on it a blank item is created. This can easily be deleted by using the following:

unset($parts[0]);

Add new comment

The content of this field is kept private and will not be shown publicly.