PHPプログラムに関する各種メモ書き

PHPで相対パスから絶対URL(URI)を作成する。または絶対パスを返す。

元となるURLとそれに対する相対パスを指定すると絶対URLを作成する関数です。

元URL:http://www.test.com/gallery/index.html
相対パス:../contact.html
URL:http://www.test.com/contact.html

使い方

$url = make_uri('元url','相対パス');

です。

関数 make_uri

//================ make_uri:version 1.4
function make_uri($base='', $rel_path=''){
    $base = preg_replace('/\/[^\/]+$/','/',$base);
    $parse = parse_url($base);
    if (preg_match('/^https\:\/\//',$rel_path) ){
        return $rel_path;
    }
    elseif ( preg_match('/^\/.+/', $rel_path) ){
        $out = $parse['scheme'].'://'.$parse['host'].$rel_path;
        return $out;
    }
    $tmp = array();
    $a = array();
    $b = array();
    $tmp = preg_split("/\//",$parse['path']);
    foreach ($tmp as $v){
        if ($v){  array_push($a,$v); }
    }
    $b = preg_split("/\//",$rel_path);
    foreach ($b as $v){
        if ( strcmp($v,'')==0 ){ continue; }
        elseif ($v=='.'){}
        elseif($v=='..'){ array_pop($a); }
        else{ array_push($a,$v); }
    }
    $path = join('/',$a);
    $out = $parse['scheme'].'://'.$parse['host'].'/'.$path;
    return $out;
}

元URLと相対パスから絶対パス(ドキュメントルートからのパス表記)を返す関数( make_apath )はこちら。

//============= make_apath:version 1.1
function make_apath($base='', $rel_path=''){
	$base = preg_replace('/\/[^\/]+$/','/',$base);
	$parse = parse_url($base);
	if (preg_match('/^https\:\/\//',$rel_path) ){
		return $rel_path;
	}
	elseif ( preg_match('/^\/.+/', $rel_path) ){
		$out = $parse['scheme'].'://'.$parse['host'].$rel_path;
		return $out;
	}
	$tmp = array();
	$a = array();
	$b = array();
	$tmp = preg_split("/\//",$parse['path']);
	foreach ($tmp as $v){
		if ($v){  array_push($a,$v); }
	}
	$b = preg_split("/\//",$rel_path);
	foreach ($b as $v){
		if ( strcmp($v,'')==0 ){ continue; }
		elseif ($v=='.'){}
		elseif($v=='..'){ array_pop($a); }
		else{ array_push($a,$v); }
	}
	$path = join('/',$a);
	return '/'.$path;
}

関連エントリー

No.501
01/21 11:58

edit

URL