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


  1. test.php = test.php
  2. /example/ = /example/index.php
  3. /example/test.php = /example/test.php
  4. /example/test.php?id=123 = /example/test.php
  5. /example/test.php/test/123 = /example/test.php/test/123


  1. test.php = test.php
  2. /example/ = /example/
  3. /example/test.php = /example/test.php
  4. /example/test.php?id=123 = /example/test.php?id=123
  5. /example/test.php/test/123 = /example/test.php/test/123


  1. test.php = test.php
  2. /example/ = /example/index.php
  3. /example/test.php = /example/test.php
  4. /example/test.php?id=123 = /example/test.php
  5. /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.

  1. $currentFile = $_SERVER["SCRIPT_NAME"];
  2. $parts = explode('/', $currentFile);
  3. $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.

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

  1. [0] =>
  2. [1] => blog
  3. [2] => example
  4. [3] => test
  5. [4] => 123
  6. [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:


Add new comment

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