Created
March 22, 2013 08:35
-
-
Save Robbert/5219787 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
# Example usage: | |
http_to_file("http://localhost/~robbert/example.com/img/"); | |
// returns "/Users/Robbert/Sites/example.com/img/"; | |
file_to_http("/Users/Robbert/Sites/example.com/style/mobile.css"); | |
// returns "http://localhost/~robbert/example.com/style/mobile.css" | |
file_to_http("/Users/Robbert/Sites/example.com/../"); | |
// returns "http://localhost/~robbert/" | |
file_to_http("/Users/Robbert/Sites/example.com/symlink-to-otherwebsite.org-style/"); | |
// returns "http://localhost/~robbert/otherwebsite.org/style/" | |
*/ | |
function magic($http, $file) | |
{ | |
$http_dir = dirname($http); | |
$file_dir = dirname($file); | |
$http_trail = array_reverse(explode('/', $http_dir)); | |
$file_trail = array_reverse(explode('/', $file_dir)); | |
$l = min(count($http_trail), count($file_trail)); | |
$i = 0; | |
while ($i < $l) | |
{ | |
if ($http_trail[$i] !== $file_trail[$i]) | |
{ | |
// $i++; | |
break; | |
} | |
$i++; | |
} | |
$http_root = implode('/', array_reverse(array_slice($http_trail, $i))) . '/'; | |
$file_root = implode('/', array_reverse(array_slice($file_trail, $i))) . '/'; | |
return array($http_root, $file_root); | |
} | |
function http_to_file($uri) | |
{ | |
$roots = magic($_SERVER['SCRIPT_NAME'], $_SERVER['SCRIPT_FILENAME']); | |
$parts = parse_url($uri); | |
$path = $parts['path']; | |
return str_replace($roots[0], $roots[1], $path); | |
} | |
function file_to_http($path) | |
{ | |
$resolved = realpath($path); | |
if ($resolved === false) | |
return ""; | |
else | |
$path = $resolved; | |
$roots = magic($_SERVER['SCRIPT_NAME'], $_SERVER['SCRIPT_FILENAME']); | |
return str_replace($roots[1], $roots[0], $path); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment