PHP | Get URL with Parameter
To get the full URL of a current page with GET parameters, we use the $_SERVER global variable. We need the current URL to perform different types of works.
For complete URL with protocol, server name, 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
?>
The 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 gives the 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 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 gives domain name such as "www.example.com".
{$_SERVER['REQUEST_URI']}
This return request query of your page. This returns all the string after your domain name, such as "page.php?id=10".
For only the 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 returns a query string only that can be used to another 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 global variables to access the GET parameter.
<?php
echo $_GET['id'].'<br>';
echo $_GET['name'].'<br>';
echo $_GET['class'];
// Output will be:
// 10
// abc
// 5
?>