Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Sponsored Ads

Detecting the Absolute URI

In PHP there's a function called parse_url which splits a given absolute url into various parts as an array.

PHP
<?php
function AbsURI()
 {
        $ThisLink = 'http'.(isset($_SERVER["HTTPS"]) ? $_SERVER["HTTPS"] == 'off' ? '' : 's' : '').
                    '://'.
                    $_SERVER['HTTP_HOST'].
                    $_SERVER['REQUEST_URI'];

        $UrlParts = parse_url($ThisLink);

        $Path = $UrlParts['path'];

        // Get rid of filename.html in /folder1/folder2/filename.html
        $Path = preg_replace('#(/)([^/]*?\..*?$)#i', '$1', $Path);

        // Make it standard to have trailing / at the end of a foldername
        if (substr($Path, -1) != '/')
         $Path .= '/';
        
        $absURI = $UrlParts['scheme'].'://'.$UrlParts['host'].$Path;

        return $absURI;
 }
?>
You can probably get the absolute URI with something as simple as :
PHP
<?php
$s = substr($_SERVER["SCRIPT_FILENAME"], strlen($_SERVER["DOCUMENT_ROOT"]));
// Not very sure if the above always evaluates to $_SERVER["SCRIPT_NAME"]

$ThisPath = 'http'.
            (isset($_SERVER["HTTPS"]) ? $_SERVER["HTTPS"] == 'off' ? '' : 's' : '').
            '://'.$_SERVER['HTTP_HOST'].
            substr($s, 0, strrpos($s, '/') + 1);
?>
but unfortunately, how filename & directory name values are stored in $_SERVER varies in server setup and relying on it may not be 100% accurate, though in 99% of the cases, it should do just fine.

There's another reason to use the 2nd snippet instead of the 1st - that's if a RewriteRule is used for the given current url ($ThisLink).
Lets say I had the 1st code snippet in absURI.php in test folder in my document root. So http://localhost/test/absURI.php would be the link. And something like this in my .htaccess file :
Apache
RewriteEngine On
RewriteRule ^fakefolder/test\.html$ absURI.php
and I access the url using http://localhost/test/fakefolder/test.html?a=2&b=c
AbsURI() will end up returning http://localhost/test/fakefolder/ which would be incorrect.

Tested on different hosts having Apache 2.0.x.
Vanakkam !

0 comments: