Get the current URL

If you already know some information about the URL you can use that information to replace the respective part.

Start with an empty path

<?php
$path 
"";
?>

Check for the protocol (ie. http, cgi)
If you know the protocol is http you can replace this accordingly.

<?php
// SERVER_PROTOCOL is in the form "protocol/rev#", this strips the revision
$path .= strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/");
?>

Check if secure (HTTPS)
The HTTPS element will be non-empty if the script was queried through HTTPS. However, if HTTPS is not used some web servers (ie. IIS) will not leave the HTTPS element empty but will set it to the value 'off'.

<?php
$path 
.= (empty($_SERVER["HTTPS"]) ? "": ($_SERVER["HTTPS"]=='on') ? "s""")."://";
?>

or
<?php
$path 
.= ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') ? "s" "")."://";
?>

Add the server name (ie. www.example.com)

<?php
path 
.= $_SERVER['SERVER_NAME'];
?>

Check for non-standard ports
If the default port is used (80 for http or 443 for https) it is not displayed.

<?php
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') {
    if(
$_SERVER['SERVER_PORT']!='443') {
        
$path .= ":".$_SERVER['SERVER_PORT'];
    }
}
else {
    if(
$_SERVER['SERVER_PORT']!='80') {
        
$path .= ":".$_SERVER['SERVER_PORT'];
    }
}
?>

Add the remaining path (ie. /dir/page.html)

<?php
$path 
.= $_SERVER['REQUEST_URI'];
?>

All Together

<?php
$path 
"";

// Protocol
$path .= strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")";

// 's' if HTTPS
$path .= ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') ? "
s" : "")."://";

// Server name
path .= $_SERVER['SERVER_NAME'];

// Non-standard ports
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') {
    if(
$_SERVER['SERVER_PORT']!='443') {
        
$path .= ":".$_SERVER['SERVER_PORT'];
    }
}
else {
    if(
$_SERVER['SERVER_PORT']!='80') {
        
$path .= ":".$_SERVER['SERVER_PORT'];
    }
}

// Remaining path
$path .= $_SERVER['REQUEST_URI'];
?>

Disclaimer:
The values that you get in $_SERVER are determined by the web server and to an extent the users browser. They are not guaranteed to contain any particular value. That being said, it usually works pretty well.

Notes:
There are several ways to get the remaining path. Each has a slightly different effect.
$_SERVER['REQUEST_URI'] - (used in this example) Returns the path as it is found in the HTTP request header. In other words, this is the path that the user typed into the address bar. If you are using server rewrite rules, the original, not the rewritten URI will be returned.
$_SERVER['PHP_SELF'] - Returns the filename of the currently executing script relative to the document root.

If the URL http://www.example.com/directory/index.php?a=test is entered:
$_SERVER['REQUEST_URI'] == /directory/index.php?a=test
$_SERVER['PHP_SELF'] == /directory/index.php?

If you omit the HTTPS check, be sure to append the ."://" to one of the included parts.