Code

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

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 !

1 comments:

gabimacchi said...

Casino-Home-Map.com - Mapyro
MapYRO is a 의왕 출장샵 fully 의정부 출장마사지 functional, modern, interactive, and automated mobile casino 제주도 출장마사지 application. To see more information or find 제주 출장마사지 out more 문경 출장안마 about its, click here.