How to get current page url in PHP ?
The goal of this article is to give you a piece of code that allows you to get the URL of the current visited page. But you will need some knowledge of PHP or programming languages to get by.
To obtain the URL of the web page displayed, you will need to retrieve three pieces of information in your script:
The protocol used by the web server: http or its secure version, https using the $ _SERVER variable, PHP variable which contains a lot of information about the server. We will therefore use $ _SERVER [‘HTTPS’] to find out if the server is using the secure version of http or not.
The domain name of the site using $ _SERVER [‘HTTP_HOST’] which allows you to retrieve the domain name of the site of the visited page (or by default its IP address if the site does not have a domain name).
The current page you are visiting. If you just want to get the page, preferably use $ _SERVER [‘PHP_SELF’]. However, it can be very useful to retrieve the parameters of the query, that is, anything after the question mark (?). Ex: index.php? Categorie = 3 & page = 2 In this specific case, we will rather use $ _SERVER [‘REQUEST_URI’] to obtain the full URL of the current page.
Here is my code to get the address of the current page:
<?php // get the protocol if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') $url = "https://"; else $url = "http://"; // get IP address $url .= $_SERVER['HTTP_HOST']; // get the URI $url .= $_SERVER['REQUEST_URI']; // displays the URL of the current page echo $url; ?>
I hope this has been useful to you!