How To Get Current URL In PHP
Last Updated : Jul 1, 2023
IN - PHP
In this tutorial we will show you the solution of how to get current URL in PHP, sometimes, due to some needs or something else, we want to get the current URL in php.
This question is also as from view of interview. Now, let us understand this with the help of codes.
Here, inside this article we going to use a super global variable that is $_SERVER. Yes, the $_SERVER is a variable in php that contains the details related to headers, paths and script locations.
The status of HTTP gets saved in the $_SERVER[‘HTTPS’].
Step By Step Guide On How To Get Current URL In PHP :-
Here, below we are going to show you a example to get current URL value from page and also checks whether the $_SERVER[‘HTTPS’] exists or not.
<?php if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') $url = "https://"; else $url = "http://"; // Append the host(domain name, ip) to the URL. $url.= $_SERVER['HTTP_HOST']; // Append the requested resource location to the URL $url.= $_SERVER['REQUEST_URI']; echo $url; ?>
- Here, we hope that you understand the basic structure of php. That what are php opening and closing tags and how to enter data in database.
- Now, for hint <?php is the opening tag of php wheras the ?> the closing tag of php. All the data of php is written inside these codes.
- Now, our next step is to check HTTPS, and this can be done with the help of isset. You can go through our codes it you want to see how to use isset.
- Now, here we checks server with parameter https and check its value is on or not. If it becomes true then the url gets stored into $url variable created there, if not then it checks to http server and save its url.
- The difference between https and http is that https is secured way of browsing whereas http is unsecured.
- Now, in next step we appends the host to the url. With the help of http_host. Here, this code is used inside the $_server which is global variable and can be used anywhere in php.
- Now, in our last step, here we append the requested resource location to url with the help of REQUEST_URI. This is also written inside our gloabal variable that is $_SERVER.
- Hence, it is the full code to get the current URL in php. but one thing has left that is to print the url.
- As, we mostly do, we use echo to print the url. We all know that our URL is stored inside $url. So, we write here echo $url. And at this step our url get printed to show on screen, we hope that you understand this method properly.
At last in conclusion, here we can say that with the help of this article we are able to get current url value in php. I hope this tutorial on how to get current URL in PHP helps you.