06 May 2010

PHP: Ultimate get/fetch RELATIVE PATH function between 2 folders/directories/files/pages or root dir

I wrote these functions today when everything I found online that attempted the same job was either too bulky, or too restrictive. It took me flippin ages - far longer than it should have! But it has huge functionality and will be a great addition to the arsenal. The main function relpath basically calculates the relative path from anywhere to anywhere on the same domain. Possible uses are listed below:
  1. Get relative path from the current page to the root directory of the local domain (rootpath)...
    echo relpath(); //outputs ../../ or something similar
  2. Get relative path from the current page to any other file/folder on the domain...
    echo relpath("/scripts/javascripts/jsmin/min.js"); //outputs ../../jsmin/min.js
  3. Get relative path from any file/folder on the domain to any other file/folder on the domain...
    echo relpath("/scripts/connect.php","/scripts/javascripts/jsmin"); //outputs ../../scripts.connect.php
Full functions with details and comments below.


URL Input Formats:

To save as much coding time as possible, relpath is very sympathetic and will accept absolute or relative urls with or without query strings, trailing slashes, www subdomain or http protocall as in examples below:
 
  • http://www.website.com/scripts/javascripts/jsmin/min.js
  • http://website.com/scripts/javascripts/jsmin/
  • www.website.com/scripts/javascripts/jsmin
  • website.com/scripts/javascripts/jsmin
  • /scripts/javascripts/jsmin/min.js (relative path from root dir)
  • /scripts/javascripts/jsmin/min.js?p=compress
  • NOT: scripts/javascripts/jsmin/min.js (needs beginning / )


The Functions:
Please see right hand pane before copying! >>


//RETURN RELATIVE PATH $from FILE/DIRECTORY TO $to FILE/DIRECTORY:
//default returns relative path from current page to root directory
function relpath($to=0,$from=0){
 $from=pathFromRoot($from,1);
 if($to){
  $basename='/'.basename($to);
  $to=pathFromRoot($to,1);
 }else{//return path to root dir:
  return(str_repeat("../",count($from)));
 }
 
 //find point where paths branch by discarding mataching directories:
 for($i=0;$i< count($from);$i++){
  if($from[$i]==$to[$i]){
   unset($from[$i]);
   unset($to[$i]);
  }
 }
 //compile result:
 $result=str_repeat("../",count($from)); //write relative path to the branching point
 $result.=implode('/',$to); //write path to target direcory
 return($result.$basename);
}

//CONVERT A RELATIVE PATH TO AN ABSOLUTE PATH:
function abspath($relPathFromRoot=0,$domain=0){
 if(!$relPathFromRoot){$relPathFromRoot=$_SERVER['PHP_SELF'];}//defaults to current page (calling script)
 if(!$domain){$domain=$_SERVER['HTTP_HOST'];}//defaults to current domain
 return "http://".$domain.str_replace(array('http://','www.',$domain),'',$relPathFromRoot);
}
//RETURN STRING URL OR ARRAY OF DIRECTORIES FROM ROOT: dir1/dir2/etc OR array("dir1", "dir2", etc);
function pathFromRoot($tofile=0,$returnArray=0,$remote=0){
 $tofile=abspath($tofile);
 $path=trim(parseUrl($tofile,'path'),'/');
 return($returnArray ? explode('/',$path) : $path);
}

//RETURNS ARRAY OF COMPONANT PARTS OF AN ABSOLUTE URL:
function parseUrl($url,$returnKey=0) {
 $r  = "^(?:(?P\w+)://)?";
 $r .= "(?:(?P\w+):(?P\w+)@)?";
 $r .= "(?P(?:(?P[-\w\.]+)\.)?" . "(?P[-\w]+\.(?P\w+)))";
 $r .= "(?::(?P\d+))?";
 $r .= "(?P[\w/]*/(?P\w+(?:\.\w+)?)?)?";
 $r .= "(?:\?(?P[\w=&]+))?";
 $r .= "(?:#(?P\w+))?";
 $r = "!$r!";// Delimiters
 preg_match ( $r, $url, $out );
 $out['path']=str_replace($out['file'],'',$out['path']); //hack fix
    return ($returnKey ? $out[$returnKey] : $out);
}

NOTES:
This is for Unix servers but could be tweaked for Windows servers.
Functions could possibly could do with some performance improvements (I'm open to suggestions!)

3 comments:

Anonymous said...

Great concept / work!

It seems your ?P labels got stripped in the html. I was able to find them by viewing the source, however.

Just an FYI for anyone else who scratched their head for a while like me!

Serry Lock said...

I am generally stumbled by the way you uncommon out staying away from on every single little detail. It can be truly going to help me a great offer. I kept up the criticalness of keeping human/others seeing touch with the understudies and people in this season of cutting edge guideline.
Ecommerce website design

Meiqing Xu said...

ralph lauren outlet
true religion outlet
jordan shoes
coach outlet
ugg outlet
nike air force 1
canada goose sale
gucci handbags
nike shoes
kevin durant shoes
20161228caiyan

Post a Comment

Cron Design Studio: Dublin based web design & software development