PHP get current URL

Question

Answers ( 1 )

    0
    2024-01-11T18:05:21+00:00

    To obtain the full URL of the current page in PHP, you can use the $_SERVER superglobal array which contains information about headers, paths, and script locations. The following code demonstrates how to construct the full URL:

    <?php
    function getCurrentUrl() {
        $protocol = 'http';
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
            $protocol = 'https';
        }
        $url = $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        return $url;
    }
    
    echo getCurrentUrl();
    ?>
    

    This function checks if the connection is HTTPS and then constructs the URL accordingly. It uses $_SERVER['HTTP_HOST'] to get the domain name (or IP address) and $_SERVER['REQUEST_URI'] to get the URI of the current page.

    Remember, this method will work in most typical scenarios, but in certain server configurations, additional checks or modifications might be necessary.

Leave an answer