OK

CSSJockey websites use cookies to give you a better user experience on our websites. Visit our Privacy and Cookie policy to get more information about cookies, including how you could opt-out.

How-to: Get Current Url in PHP with or without Query String

In each PHP website, we need to find out the current URL of the page and here's the PHP code to find out...

published: 2 years ago

In each PHP website, we need to find out the current URL of the page and here’s the PHP code to find out the current URL of the page a user is browsing with or without the query string.

function currentUrl( $trim_query_string = false ) {
    $pageURL = (isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on') ? "https://" : "http://";
    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    if( ! $trim_query_string ) {
        return $pageURL;
    } else {
        $url = explode( '?', $pageURL );
        return $url[0];
    }
}

I like to keep such functions in a helpers class so I can use them anywhere in the app. To use it in a PHP class you can use the following code:

public function currentUrl( $trim_query_string = false ) {
    $pageURL = (isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on') ? "https://" : "http://";
    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    if( ! $trim_query_string ) {
        return $pageURL;
    } else {
        $url = explode( '?', $pageURL );
        return $url[0];
    }
}
 
 

pre-built solutions

Speed-up the launch of your web projects with our ready-to-use plugins, themes and widgets!

This block enables a user to signup for a newsletter or to simply submit their email address for an offer. You can custo...
This 3 columns Block helps you to showcase the FAQs section anywhere on your website. You can add any number of FAQs and...