How To Get Url In Php

When working with PHP, you may often find yourself in a situation where you need to retrieve the current URL of the webpage. This could be to generate dynamic content, create breadcrumbs, or even for logging and analytics purposes. In this blog post, we will explore different ways to get the URL in PHP.

Method 1: Using the $_SERVER Superglobal

The most common method to get the URL in PHP is by using the $_SERVER superglobal array. This array contains information about the server environment, including HTTP headers, server paths, and script locations.

To get the current URL, we can combine several elements of the $_SERVER array. Here’s an example of how to do it:

function get_current_url() {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
    $domain = $_SERVER['HTTP_HOST'];
    $path = $_SERVER['REQUEST_URI'];
    return $protocol . $domain . $path;
}

$current_url = get_current_url();
echo $current_url;
    

In the example above, we first determine the protocol (HTTP or HTTPS) by checking the $_SERVER[‘HTTPS’] variable. We then concatenate the protocol, domain (stored in $_SERVER[‘HTTP_HOST’]), and path (stored in $_SERVER[‘REQUEST_URI’]) to create the full URL.

Method 2: Using the $_GET Superglobal

Another method to get the URL in PHP is by using the $_GET superglobal array. This array contains all the variables sent via the HTTP GET method, which are usually appended to the URL as query parameters.

To get the current URL along with any query parameters, we can modify the previous function like this:

function get_current_url_with_query() {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
    $domain = $_SERVER['HTTP_HOST'];
    $path = $_SERVER['REQUEST_URI'];
    $query = $_SERVER['QUERY_STRING'];
    return $protocol . $domain . $path . "?" . $query;
}

$current_url_with_query = get_current_url_with_query();
echo $current_url_with_query;
    

In this modified function, we simply add the query parameters (stored in $_SERVER[‘QUERY_STRING’]) to the end of the URL, separated by a question mark (?).

Conclusion

In this blog post, we discussed two methods to get the URL in PHP using the $_SERVER and $_GET superglobals. These methods provide you with a straightforward way to retrieve the current URL and can be easily adapted to suit your specific requirements. Remember to always sanitize and validate user input when working with URLs to prevent security vulnerabilities.