find file

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
devendra-m
Forum Contributor
Posts: 111
Joined: Wed Sep 12, 2007 3:16 am

find file

Post by devendra-m »

You can use following code to find full path of the file you wanted

Code: Select all

<?	
	$main="test";
	define('ROOT_PATH',str_replace('//','/',ereg_replace("((.*)/?)", "\\2", $_SERVER['DOCUMENT_ROOT']).(trim($main)!=''?"/".$main:'')));
	function traverse($root,$destination)
	{
		$handle = opendir($root);
		while (false !==($file=readdir($handle))) 
			if($file != '.' && $file != '..')
			{
				$full_path=$root."/".$destination;				
				if(file_exists($full_path))				
					return $full_path;
		
				$path=$root."/".$file;
				if(is_dir($path))
					if($full_path=traverse($path,$destination))
						return $full_path;
			}
	}
	function absolutePathServer($destination)
	{
		if($full_path=traverse(ROOT_PATH,$destination))
			return $full_path;
		else 
			return $destination;
	}
	function absolutePathClient($destination)
	{
		if($full_path=traverse(ROOT_PATH,$destination))
			return "http://".str_replace('//','/',str_replace($_SERVER['DOCUMENT_ROOT'],$_SERVER['HTTP_HOST']."/", $full_path));
		else 
			return $destination;
	}
?>
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

alternatively:

Code: Select all

realpath($destination);

function absolutePathClient ($destination) {
  if (strpos(realpath($destination), $_SERVER['DOCUMENT_ROOT']) === 0) {
    return substr(realpath($destination), strlen($_SERVER['DOCUMENT_ROOT']));
  } else {
    return false; // or throw new Exception('File outside of document root'); or whatever.
  }
}
Post Reply