21

I am using following code to get the current URL

$current_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

Is there any other way to get the same, or may be better way to get current URL?

Thanks.

JohnP
  • 49,507
  • 13
  • 108
  • 140
I-M-JM
  • 15,732
  • 26
  • 77
  • 103

2 Answers2

35

From the reference:

<?php

function curPageURL() {
    $pageURL = 'http';

    if ($_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";

    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }

    return $pageURL;
}
?>
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • I believe you have to be careful with checking the HTTPS value because it differs between Apache and IIS. – Jacob Mar 07 '11 at 05:43
  • 1
    The link for the must read article is down, can anyone share it again ? – 4wk_ Aug 12 '14 at 07:56
9

You have to be careful relying on server variables, and it depends what the webserver wants to give you... Here's a fairly failsafe way to get the URL.

$url = '';

if (isset($_SERVER['HTTPS']) && filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN))
    $url .= 'https';
else
    $url .= 'http';

$url .= '://';

if (isset($_SERVER['HTTP_HOST']))
    $url .= $_SERVER['HTTP_HOST'];
elseif (isset($_SERVER['SERVER_NAME']))
    $url .= $_SERVER['SERVER_NAME'];
else
    trigger_error ('Could not get URL from $_SERVER vars');


if ($_SERVER['SERVER_PORT'] != '80')
  $url .= ':'.$_SERVER["SERVER_PORT"];

if (isset($_SERVER['REQUEST_URI']))
    $url .= $_SERVER['REQUEST_URI'];
elseif (isset($_SERVER['PHP_SELF']))
    $url .= $_SERVER['PHP_SELF'];
elseif (isset($_SERVER['REDIRECT_URL']))
    $url .= $_SERVER['REDIRECT_URL'];
else
    trigger_error ('Could not get URL from $_SERVER vars');

echo $url;
Jacob
  • 8,278
  • 1
  • 23
  • 29