Given a true path of:

PHP Output Notes
$_SERVER['DOCUMENT_ROOT']; /var/www true document root
$_SERVER['HTTP_HOST'] Host name
$_SERVER['PHP_SELF'] /stuff/more/file.php Path of current file

So combining $_SERVER['HTTP_HOST'] with $_SERVER['PHP_SELF'] would get the full path to the file ie:

PHP Output

The pathinfo() method can then be used to return an associate array of useful path information. These include:

The true path to the directory ie /var/www/stuff/more
The actual file name ie file.php
The file extension ie php
The file name minus the extension

So for example the following would retrieve the current directory.

The following creates an array using pathinfo.

$myPathInfo = pathinfo($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF']);

... and then we have access to:

PHP Output
$myPathInfo['dirname']; /var/www/stuff/more
$myPathInfo['basename']; file.php
$myPathInfo['extension']; php
$myPathInfo['filename']; file

The Referrer

Another couple of useful tricks to get referrer data - ie from whence you came. The value of $_SERVER['HTTP_REFERER'] gives the full url of the referrer. This URL can then be feed into the parse_url method to get an array of lovely values.

$myURLInfo = parse_url($_SERVER['HTTP_REFERER']);

... and then we have access to:

PHP Access to
$myURLInfo['host']; host name ie
$myURLInfo['query']; name/values pairs after the question mark ?arg=value
$myURLInfo['fragment']; anchors after the #

And an example would be:

// we arrived from
$referringSite = $_SERVER['HTTP_REFERER'];
$myDomainInfo = parse_url($referringSite);
$myReferrerHost =  $myDomainInfo['host'];
// $myReferrerHost is equal to

If you found these useful you might also like this post PHP String Manipulation: Retrieving Parent Directories from a URL

Getting the Video ID from a youtube URL

Here is a quick use case. If you have the URL of a youtube video but just want the v value from the query string this will do the trick.

$myURLInfo = parse_url('');
$values = parse_str($myURLInfo['query']);
echo $v;
// output pAFptrSuw7E

... and here is a function version:

function getQSvalue($url, $val){
	$urlInfo = parse_url($url);
	return $$val;

echo getQSvalue('', 'v');

Tip: See Referencing Dynamic Variables Names in PHP with Double Dollars to explain the double $$.

One Thought to “Getting Path Information with PHP”

  1. Thanks for this great post, from your smart code I discover parse_str() function and using double $$, and your final getQSvalue function is awesome can return any parameter value using its name. really great site.

Leave a Comment