annotate php/rel2abs.php @ 3141:335bc77627e0 tip

fixing discrete interface to allow labels to display
author Dave Moffat <me@davemoffat.com>
date Mon, 26 Jul 2021 12:15:24 +0100
parents 464c6c6692d6
children
rev   line source
nicholas@2249 1 <?php
nicholas@2249 2
nicholas@2249 3 //http://stackoverflow.com/questions/4444475/transfrom-relative-path-into-absolute-url-using-php
nicholas@2249 4 function rel2abs($rel, $base)
nicholas@2249 5 {
nicholas@2249 6 /* return if already absolute URL */
nicholas@2249 7 if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel, 0, 2) == '//') return $rel;
nicholas@2249 8
nicholas@2249 9 /* queries and anchors */
nicholas@2249 10 if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
nicholas@2249 11
nicholas@2249 12 /* parse base URL and convert to local variables:
nicholas@2249 13 $scheme, $host, $path */
nicholas@2249 14 extract(parse_url($base));
nicholas@2249 15
nicholas@2249 16 /* remove non-directory element from path */
nicholas@2249 17 $path = preg_replace('#/[^/]*$#', '', $path);
nicholas@2249 18
nicholas@2249 19 /* destroy path if relative url points to root */
nicholas@2249 20 if ($rel[0] == '/') $path = '';
nicholas@2249 21
nicholas@2249 22 /* dirty absolute URL */
nicholas@2249 23 $abs = "$host$path/$rel";
nicholas@2249 24
nicholas@2249 25 /* replace '//' or '/./' or '/foo/../' with '/' */
nicholas@2249 26 $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
nicholas@2249 27 for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
nicholas@2249 28
nicholas@2249 29 /* absolute URL is ready! */
nicholas@2249 30 return $scheme.'://'.$abs;
nicholas@2249 31 }
nicholas@2538 32 ?>