Skip to content

Instantly share code, notes, and snippets.

@anon5r
Last active November 15, 2019 12:04
Show Gist options
  • Save anon5r/7cd168a5db9e1b44afe04f8b93131cf5 to your computer and use it in GitHub Desktop.
Save anon5r/7cd168a5db9e1b44afe04f8b93131cf5 to your computer and use it in GitHub Desktop.
Generate absolute URL by relational path with base URL
<?php
/**
* 相対パスから絶対URLを返却する
*
* @param string $base ベースURL, 絶対URL
* @param string $relational_path 相対パス
* @return string 相対パスの絶対URL
* @link http://logic.stepserver.jp/data/archives/501.html
* @link http://blog.anoncom.net/2010/01/08/295.html
* @link https://blog.anoncom.net/2010/01/phpurluri.html
*/
function createUri( $base = '', $relational_path = '' ) {
$parse = array(
'scheme' => null,
'user' => null,
'pass' => null,
'host' => null,
'port' => null,
'path' => null,
'query' => null,
'fragment' => null,
);
$parse = parse_url ( $base );
// パス末尾が / で終わるパターン
if ( strpos( $parse['path'], '/', ( strlen( $parse['path'] ) - 1 ) ) !== FALSE ) {
$parse['path'] .= '.'; // ダミー挿入
}
if ( preg_match ( '#^https?\://#', $relational_path ) ) {
// 相対パスがURLで指定された場合
return $rel_path;
} elseif ( preg_match ( '#^/.*$#', $relational_path ) ) {
// ドキュメントルート指定
return $parse['scheme'] . '://' . $parse ['host'] . $relational_path;
} else {
// 相対パス処理
$basePath = explode ( '/', dirname ( $parse ['path'] ) );
$relPath = explode ( '/', $relational_path );
foreach ( $relPath as $relDirName ) {
if ($relDirName == '.') {
array_shift ( $basePath );
array_unshift ( $basePath, '' );
} elseif ($relDirName == '..') {
array_pop ( $basePath );
if ( count ( $basePath ) == 0 ) {
$basePath = array( '' );
}
} else {
array_push ( $basePath, $relDirName );
}
}
$path = implode ( '/', $basePath );
return $parse ['scheme'] . '://' . $parse ['host'] . $path;
}
}
<?php
/**
* テストコード
* Testing code
*/
$base = 'http://example.com/path/to/url';
$pathes[] = '/';
$pathes[] = '/index.html';
$pathes[] = '/foo/bar/baz/';
$pathes[] = './foo/bar/baz';
$pathes[] = '../../../foo/bar/baz/index.html';
$pathes[] = 'foo/bar/baz.html';
$pathes[] = 'foo/bar/baz/../index.html';
foreach ( $pathes as $path ) {
echo createUri($base, $path) . PHP_ROL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment