Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to get current URL in PHP?

Answer: Using PHP $_SERVER Variable

The superglobal variables are the predefined variables that are accessible in all scope within the PHP code. The $_SERVER is a superglobal variable in PHP. This variable holds the server's information and environment, such as HTTP header, path, script location, etc.

Example: Get Current URL in PHP

In the given example, we are going to use the $_SERVER variable. While using this variable, we have to use the two separate indices to get each part of the URL of the current page. The first index consists of the host and the second index consists of the page name.

<!DOCTYPE html>
<html>
<head>
	<title>Current URL in PHP</title>
</head>
<body>
	<?php
	$currentPageUrl = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
	echo "Current page URL is: " . $currentPageUrl;
	?>
</body>
</html>

Output

Current page URL is: http://localhost/index.php

Using isset() function

The basic functionality of isset() function is to check whether the variable is set or not. This method returns true if the variable is set and is not null otherwise it returns false.

With the help of isset() function, we can check whether the HTTPS is enabled or not. We have to use the $_SERVER['HTTPS'] in isset() function to check whether it exists or not. If it is on then HTTPS is enabled and we can append HTTPS within the URL.

Example: Getting current URL

In this example, first, we have used the isset() method to check whether the HTTPS is enabled or not after that we have used the two indices $_SERVER['HTTP_HOST'] and $_SERVER['REQUEST_URI'] to get each part of the URL.

<!DOCTYPE html>
<html>
<head>
	<title>Getting current URL</title>
</head>
<body>
	<?php  
		if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')   
		    $url = "https://";   
		else  
		    $url = "http://";   

		$url.= $_SERVER['HTTP_HOST'];   
		$url.= $_SERVER['REQUEST_URI'];    
		echo $url;
	?>   
</body>
</html>

Output


http://localhost/index.php

Conclusion

In this lesson, we have discussed how to get the current URL of the page in PHP. So, we can get the current URL in PHP using the super global variable $_SERVER as this is the super global variable and can be accessible in any scope.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.