Ad

Create a function that returns a working relative path from the base path to the given target path.

The base path and the target path are absolute.

Ex:
Target: /httpdocs/admin/img/icons/
Base: /httpdocs/admin/
Result: img/icons

Ex 2:
Target: /httpdocs/admin/
Base: /httpdocs/admin/
Result: .

Ex 3:
Target: /httpdocs/
Base: /httpdocs/admin/
Result: ..

Ex 4:
Target: /httpdocs/img/
Base: /httpdocs/admin/
Result: ../img

function getRelativePath($base = '/', $target = '/')
{
  $out = array();
  
  $base_ex = explode('/', $base);
  $target_ex = explode('/', $target);
  
  //Find common ancestor
  $max = min(count($base_ex), count($target_ex));
  for($i = 0; $i < $max; $i++)
  {
    $b = $base_ex[$i];
    $t = $target_ex[$i];
    
    if($b != $t) break;
  }
  $common = $i;
  
  $diff = (count($base_ex) - 1) - $common;
  
  /*
  $diff = 0:
  Target:   /httpdocs/admin/
  Base:     /httpdocs/admin/
  
  $diff > 0:
  Target:   /httpdocs/
  Base:     /httpdocs/admin/
  */
  
  for($i = 0; $i < $diff; $i++)
  {
    $out[] = '..';
  }
  
  $rest = array_slice($target_ex, $common);
  
  $out = array_merge($out, $rest);
  
  if(count($out) == 0) $out[] = '.';
  
  return join('/', $out);
}

echo getRelativePath('/httpdocs/admin/', '/httpdocs/admin/img/icons/');
echo "\n";

echo getRelativePath('/httpdocs/admin/', '/httpdocs/admin/');
echo "\n";

echo getRelativePath('/httpdocs/admin/', '/httpdocs/img/');
echo "\n";