Php Code to Get Current Webpage URL
PHP having the super global variables $_SERVER to get currently using page URL
URL – http://www.tobbynews.com/page/2.php
$_SERVER['PHP_SELF']
PHP_SELF will return the currently working webpage with their directory path ( /page/2.php )
$_SERVER['SCRIPT_NAME']
SCRIPT_NAME is introduced in CGI, and it also returns the currently working webpage ( /page/2.php )
$_SERVER['HTTP_HOST']
HTTP_HOST is a client controlled value and returns domain name (http://www.tobbynews.com)
$_SERVER['SERVER_NAME']
SERVER_NAME is server controlled value (http://www.tobbynews.com)
$_SERVER['REQUEST_URI']
REQUEST_URI will return currently working webpage with directory path and also query string ( /page/2.php )
Difference Between $_SERVER['PHP_SELF'], $_SERVER['SCRIPT_NAME'] and $_SERVER['REQUEST_URI']
$_SERVER['PHP_SELF'], $_SERVER['SCRIPT_NAME'] & $_SERVER['REQUEST_URI'] - All this super global variable will return the same output i.e., /page/2.php
$_SERVER['REQUEST_URI'] is unique from all this, because this will get query string from the webpage but other two wont give query string.
Example: URL: http://www.tobbynews.com/page/2.php?name=tobby
1 2 3 4 5 6 7 8 9 |
<?php
echo "PHP_SELF - ".$_SERVER['PHP_SELF'];
echo "SCRIPT_NAME - ".$_SERVER['SCRIPT_NAME'];
echo "REQUEST_URI - ".$_SERVER['REQUEST_URI'];
?>
|
Output:
PHP_SELF – /page/2.php
SCRIPT_NAME – /page/2.php
REQUEST_URI – /page/2.php?name=tobby
Here is the various methods of php code to get website name and currently using webpage.
1 2 3 4 5 6 7 8 |
<?php
$domain=$_SERVER['SERVER_NAME']; // Returns http://www.tobbynews.com
$domain1=$_SERVER['HTTP_HOST']; // Returns http://www.tobbynews.com
$url=$SERVER['PHP_SELF']; // Returns /page/2.php
$url1=$SERVER['SCRIPT_NAME']; //Returns /page/2.php
$url2=$SERVER['REQUEST_URI']; //Returns /page/2.php
echo $domain.$url1;
?>
|
OUTPUT:
http://www.tobbynews.com/page/2.php
Use of Getting Current Webpage URL
1. Making forward and back button or link in webpage
2. To submit data in a webpage through FORM input element to the same page ( i.e., sending data from form by GET or POST method to the same page )
1 2 3 4 5 |
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
....
HTML Input goes here
...
</form>
|




