JBZoo\Utils\Url::pathToRel PHP Method

pathToRel() public static method

Convert file path to relative URL
public static pathToRel ( $path ) : string
$path
return string
    public static function pathToRel($path)
    {
        $root = FS::clean(Vars::get($_SERVER['DOCUMENT_ROOT']));
        $path = FS::clean($path);
        $normRoot = str_replace(DIRECTORY_SEPARATOR, '/', $root);
        $normPath = str_replace(DIRECTORY_SEPARATOR, '/', $path);
        $regExp = '/^' . preg_quote($normRoot, '/') . '/i';
        $relative = preg_replace($regExp, '', $normPath);
        $relative = ltrim($relative, '/');
        return $relative;
    }

Usage Example

Example #1
0
 public function testPathToUrl()
 {
     $_SERVER['HTTP_HOST'] = 'test.dev';
     $_SERVER['SERVER_PORT'] = 80;
     $_SERVER['REQUEST_URI'] = '/test.php?foo=bar';
     $_SERVER['QUERY_STRING'] = 'foo=bar';
     $_SERVER['PHP_SELF'] = '/test.php';
     $_SERVER['DOCUMENT_ROOT'] = PROJECT_ROOT;
     isSame('tests/UrlTest.php', Url::pathToRel(__FILE__));
     isSame('http://test.dev/tests/UrlTest.php', Url::pathToUrl(__FILE__));
     $_SERVER['DOCUMENT_ROOT'] = str_replace('/', '\\', PROJECT_ROOT);
     isSame('tests/UrlTest.php', Url::pathToRel(__FILE__));
     isSame('http://test.dev/tests/UrlTest.php', Url::pathToUrl(__FILE__));
 }
All Usage Examples Of JBZoo\Utils\Url::pathToRel