comparison php/rel2abs.php @ 2249:30c012132427

Implementation for #21 on PHP
author Nicholas Jillings <nicholas.jillings@mail.bcu.ac.uk>
date Tue, 19 Apr 2016 14:58:40 +0100
parents
children 464c6c6692d6
comparison
equal deleted inserted replaced
2247:ae2bf6a1693e 2249:30c012132427
1 <?php
2
3 //http://stackoverflow.com/questions/4444475/transfrom-relative-path-into-absolute-url-using-php
4 function rel2abs($rel, $base)
5 {
6 /* return if already absolute URL */
7 if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel, 0, 2) == '//') return $rel;
8
9 /* queries and anchors */
10 if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
11
12 /* parse base URL and convert to local variables:
13 $scheme, $host, $path */
14 extract(parse_url($base));
15
16 /* remove non-directory element from path */
17 $path = preg_replace('#/[^/]*$#', '', $path);
18
19 /* destroy path if relative url points to root */
20 if ($rel[0] == '/') $path = '';
21
22 /* dirty absolute URL */
23 $abs = "$host$path/$rel";
24
25 /* replace '//' or '/./' or '/foo/../' with '/' */
26 $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
27 for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
28
29 /* absolute URL is ready! */
30 return $scheme.'://'.$abs;
31 }
32 ?>