PHP get URL
The PHP $_SERVER, which is a super global, contains useful information that can be used to get complete current URL of the web page.
See the example to get current URL
See the example below, that explains how getURL() function combines different pieces of PHP $_SERVER and displays the current URL.
Get URL example in PHP
The following example can be used to get the current URL in PHP. It creates a function getURL() that simply executes the statements to get the current URL. A variable $whichprotocol is returned by this function that uses PHP $_Server variables: HTTP_HOST and REQUEST_URI.
The later part simply calls this function and displays the current URL.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?php
//getURL function to get URL
function getURL()
{
/* First check if page is http or https */
$whichprotocol = $_SERVER[‘HTTPS’] == ‘on’ ? ‘https’ : ‘http’;
/* Combine different pieces of $_SERVER variable to return current URL */
return $whichprotocol.‘://’.$_SERVER[‘HTTP_HOST’].$_SERVER[‘REQUEST_URI’];
}
/*Calling getURL function to display current page URL*/
echo getURL();
?>
|
PHP get IP address example
The example below shows how to use $_SERVER, super global, to return current IP address by using SERVER_ADDR element.
1
2
3
4
5
6
7
|
<h3> How to get ip address in PHP
<?php
echo “Server Address: “.$_SERVER[‘SERVER_ADDR’];
?>
|
The $_SERVER[‘SERVER_ADDR’] is used to return server’s IP address.
Leave A Comment?