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!)

20 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!

Unknown 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

Unknown 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

Unknown said...

A number of us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.

============================================

Best web development company in Kanpur India

Riveyra Infotech Pvt Limited said...

I all the time emailed this website post page to all my friends, because if like to read it then my friends will too.

-----------------------
Best web development software Company in Kanpur

Author said...

very helpful post. i share my friends this post they really like it.
regards
best digital marketing company in kanpur.

gymgyan.com said...

thanks for sharing post and very helpful. I like it this post.

Aakash Kanaujia said...

Thanx for sharing this informative content with us
Regards
Best gaming website in Thailand

Author said...

thanks for sharing information with us.
best software development company in kanpur

Aakash Kanaujia said...

very helpful post.....
Gembet99

postshealth said...

great post.
Nugenix : A Best Tested Supplement That Boosts Your Testosterone

Author said...

awesome post very informative and helpful article.
best software development company in kanpur

shivanshu said...

Hello,
I m Really looking forward to read more. Your site is very helpful for us .. This is one of the awesome post i got the best information through your site and Visit also this site.
Click here to know who isbest software development company in kanpur

MLM Softonline said...

Awesome content in this blog
Thanx for sharing with us
Software Company in Kanpuyr

DigiBask said...

Awesome Content
Gembet99

MLM Softonline said...

Awesome blog post with ihnformative content
mlm software company

digibask said...

You are not sure on how to get your first ecommerce website development then visit best website designing company in kanpur we also help you to promot your business with the email marketing and message marketing.

Unknown said...

well explained bro
Thanks for sharing great amazing information
Regards
Best website developemnt company in balaghat

Best Software Company in Kanpur said...

Awesome Blog Post With Informative Content
Regards
What Are Digital Marketing And Digital Marketing New Strategies?

ehrichjabarri said...

“Increased state revenues, doubtlessly reaching the tens of tens of millions of dollars yearly, from funds made by amenities providing sports activities wagering and new civil penalties approved by this measure. Some portion of these revenues would reflect a shift from different existing state and native revenues. Increased state regulatory prices, doubtlessly reaching the low tens of tens of millions of dollars yearly. Some or all of these prices would 라이브카지노 be offset by the elevated income or reimbursements to the state. Increased state enforcement prices, not doubtless to|prone to} exceed several of} million dollars yearly, associated to model new} civil enforcement tool for enforcing sure gaming laws. Attack Effect First Stage - Shadow Sae Niijima Roulette Time Begins roulette spin that forces the Thieves to guess both HP, SP, or cash.

Post a Comment

Cron Design Studio: Dublin based web design & software development