Getting Path Information with PHP

Given a true path of:

/var/www/stuff/more/file.php
PHP Output Notes
$_SERVER['DOCUMENT_ROOT']; /var/www true document root
$_SERVER['HTTP_HOST'] www.mustbebuilt.co.uk 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
$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; www.mustbebuilt.co.uk/stuff/more/file.php

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

dirname
The true path to the directory ie /var/www/stuff/more
basename
The actual file name ie file.php
extension
The file extension ie php
filename
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 www.myhost.com
$myURLInfo['query']; name/values pairs after the question mark ?arg=value
$myURLInfo['fragment']; anchors after the #

And an example would be:

// we arrived from http://www.myhost.com/stuff/more/file.php
$referringSite = $_SERVER['HTTP_REFERER'];
$myDomainInfo = parse_url($referringSite);
$myReferrerHost =  $myDomainInfo['host'];
// $myReferrerHost is equal to www.myhost.com

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('https://www.youtube.com/watch?v=pAFptrSuw7E');
$values = parse_str($myURLInfo['query']);
echo $v;
// output pAFptrSuw7E

... and here is a function version:

function getQSvalue($url, $val){
	$urlInfo = parse_url($url);
	parse_str($urlInfo['query']);
	return $$val;
}

echo getQSvalue('https://www.youtube.com/watch?v=pAFptrSuw7E', 'v');

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