PHP

How to get current page URL in PHP

0
1.6k
2018 / 05 / 09

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.

Hi, I am a full-stack web developer with 5+ years of experience in working with different web technologies. Do you want to ask something? just send me a message through the contact form. Please visit my portfolio at hamzamehmood.com. Thanks