How to get the current page URL in PHP?

In PHP, you can get the current page URL by accessing the $_SERVER superglobal variable, which contains information about the current request. Specifically, you can use the ‘REQUEST_URI’ key to get the URL of the current page, as shown in the following example:

$current_url = "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo $current_url;

This code first checks if the request was made over HTTPS using the ‘HTTPS’ key in the $_SERVER superglobal. If the ‘HTTPS’ key is set, it appends an ‘s’ to the ‘HTTP’ protocol to create ‘HTTPS’. It then concatenates the protocol, and hostname, and requests URI to create the complete URL of the current page, which is stored in the $current_url variable. Finally, it echoes the current URL to the output.

Note: The following code using for the canonical script.

<?php  $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";?>
<link rel="canonical" href="<?php echo $actual_link; ?>">

Leave a Reply

Your email address will not be published. Required fields are marked *