In this tutorial we are going to see how to get URL of current page using PHP.
Tutorial Difficulty:
Basic users
Getting Current Page URL:
We are going to use PHP built-in functions to get current page URL in PHP.
- $_SERVER['HTTP_HOST']
- $_SERVER['REQUEST_URI']
Let us discuss each one seperately
Note: I was checking the code in the following URL
http://www.designscriting.com/getting-current-page-url-in-php
$_SERVER['HTTP_HOST'] function in PHP
This is a simple php function which displays the host name of current page.
Example:
<?php $hostName=$_SERVER['HTTP_HOST']; echo $hostName; ?>
Ouput:
www.designscripting.com
$_SERVER['REQUEST_URI'] function in PHP
The above function displays the remaining URL of the current page other than the host name.
Example:
<?php $pathName=$_SERVER['HTTP_HOST']; echo $pathName; ?>
Output:
/getting-current-page-url-in-php
Getting Current Page URL in PHP:
so far have seen how to get URL in parts now we are going to combine them to get complete URL in PHP
Example to get Complete URL:
<?php $pageURL="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; echo $pageURL; ?>
Output:
http://www.designscriting.com/getting-current-page-url-in-php
Please note that we have added “http://” to the final string to make the URL complete.
Related posts: