How to get current page URL in PHP

How to get current page URL in PHP

Do this

<?php
    $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    echo $url;
?>

More efficient code:

function getCurrentPageUrl() {
    $pageURL = 'http';
    if (isset($_SERVER["HTTPS"]) && $_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;
}

echo getCurrentPageUrl();

 

You can write the above code in functions file of your of your web software.

You can also fetch URL in WordPress but in this post we have mentioned native PHP solution.

Related Posts