How to Get Current Page URL in php

August 08, 2014
1K
12K


Category:
Tags:

<?php
// to get current page url, write echo get_current_page_url();
function get_current_page_url() {
    
$page_url 'http';
    if (
$_SERVER['HTTPS'] == 'on') {
        
$page_url .= 's';
    }
    
$page_url .= '://';

    if (
$_SERVER['SERVER_PORT'] != '80') {
     
$page_url .= $_SERVER['SERVER_NAME'] . ':' $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
    }
    else {
     
$page_url .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    }
    return 
$page_url;
}
?> 

Why do you need to show the port number?

If the web server is not being addressed on a standard port, it would be necessary to include it in a URL in order to point to the correct service on the machine hosting the web server. Browsers and other HTTP clients pretty much assume port :80 as a default. SSL clients pretty much assume port :443 as a default.

That said, the code should be checking not only for port :80, but also port :443 to determine whether to omit the port number. As the code is now, it would unnecessarily add port :443 to all SSL requests.

CATEGORIES