Note: you might find these PHP functions do what you are after as well Getting Path Information with PHP

This function is designed to return the file name called by a particular URL. It can also navigate up the URL to retrieve the parent directories if more of a path is needed in your application.

getDirectory(targetURL:string, [noOfDirectories:int=0 ])

function getDirectory($full, $noDir=0){
	$pos1 = strripos($full, "/");
	$path = substr($full, $pos1);
	if($noDir == 0){
	    $path = str_replace("/", "", $path);
 	   $slash1 = substr($full, 0, $pos1);
  	   $pos2 = strripos($slash1, "/");
  	   $slash2 = substr($slash1, $pos2);
  	   $path = $slash2 . $path;
  	   $full = $slash1;
   	   $pos1 = strripos($full, "/");
	return $path;

The PHP function takes a URL as its first parameter. The second parameter is optional and represents the number of directories back up the URL you wish returned. If no second parameter is provided just the file name is returned.

For example given a URL of:

If we just want the file name “search.png” then we could call:

$origPath = "";
$newPath = getDirectory($origPath);
echo $newPath;
//ouptut search.png

CodePad Demo

If you want the path including the two parent directories then the following call should be made:

$origPath = "";
$newPath = getDirectory($origPath, 2);
echo $newPath;
//ouptut /basic/images/search.png

Notice the addition of the second parameter to the getDirectory() call.

Leave a Comment