Get full url in php

172 Views

Get full url in php

PHP | Get URL with Parameter

To get full url of a current page with get parameters, we use $_SERVER global variable. We need current url to perform different type of works.

For complete URL with protocol, servername and parameters:

 <?php

echo 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

// This will return all URLs with page name. 
// http://www.example.com/page.php?id=10 OR https://www.example.com/page.php?id=10

?>

Above example will give you the full url along with GET parameters. 


Let's see the term which is used in the example:

'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://'

This code give scheme name. The status of HTTPS is saved in the Global variable $_SERVER[‘HTTPS’]. So, we use $_SERVER[‘HTTPS’] in isset() function is to check whether HTTPS is exists or not. If it is "exists", then HTTPS is enabled and we have to append "s" to "http" and complete code output is "https://".

 

{$_SERVER['HTTP_HOST']}

This code give domain name such as "www.example.com".

 

{$_SERVER['REQUEST_URI']}

This return request query of your page. This return all the string after your domain name, such as "page.php?id=10".

 


 

For only last segment name and get parameters:

http://www.example.com/folder/page.php?id=10&name=abc&class=5

This time we need only last segment or page name of the url and GET parameters "page.php?id=10&name=abc&class=5". So for this we use basename() function with $_SERVER['REQUEST_URI'].

 <?php

echo basename($_SERVER['REQUEST_URI']);

//This will return all URLs with page name. (e.g.: page.php?id=10&name=abc&class=5).

?>

 


 

For Get parameters only

http://www.example.com/folder/page.php?id=10&name=abc&class=5

This time we need only query string or GET parameter "id=10&name=abc&class=5". So for this we use $_SERVER['QUERY_STRING']. It return query string only that can be use to other url easily.

 <?php

echo $_SERVER['QUERY_STRING'];

//This will return all URLs with page name. (e.g.: id=10&name=abc&class=5).

// passing query string to another url

echo "http://www.example.com/folder1/page5.php?".$_SERVER['QUERY_STRING'];

// This will return:
// http://www.example.com/folder1/page5.php?id=10&name=abc&class=5

?>

We can also use $_GET globa variables to access the GET parameter.

 <?php

echo $_GET['id'].'<br>';
echo $_GET['name'].'<br>';
echo $_GET['class'];

// Output will be:
// 10
// abc
// 5

?>

 

Tags:-
PHP

Today spacial posts