Introduction

PHP scripts are used to retrieve the URL of a web page on the web server. There are multiple approaches to achieve this task. In this article, you will explore three approaches to get full URL in PHP.  You will use the $_SERVER superglobal array variable and its various elements to retrieve different parts of the URL. After that, those parts will be appended together to get full URL in PHP. In this way, you will get the full path of the current web page.

The necessary superglobal variables such as $_SERVER[‘HTTPS’], $_SERVER[‘REQUEST_URI’], $_SERVER[‘SERVER_PORT’] are used to get full URL in PHP. The variable HTTPS can easily retrieve the protocol in the URL of a webpage. If it returns a value “on”, then the protocol is HTTPS. And if the value returned is not equal to “on” then the protocol in the URL of the webpage is HTTP.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Are Superglobals?

PHP provides you with certain specific pre-defined variables. These variables help you retrieve the data and information about a request or its context. As their name suggests, superglobal variables have a superglobal scope. They are accessible throughout your PHP script. You can access these variables by using any function, file, or class without doing much work to create or declare a new variable inside your function or class. The primary purpose that these variables serve is to hold as well as retrieve the data from a page of an application. 

Here is a list of superglobals that are provided by PHP:

  • $GLOBALS:

 It is a type of superglobal variable that helps to access all the global variables throughout the PHP script and comes in useful when trying to get full URL in PHP. PHP provides an array $GLOBALS[ ] to hold the references of all the global variables as array elements. The index of the array represents the names of the global variables.

The following program illustrates the $GLOBALS variable in PHP.

<?php 

    // initialize two global variables

    $var1 = 100;

    $var2 = 200;  

    function getSum() {

        // store the result in global array

        $GLOBALS['result'] = $GLOBALS['var1'] + $GLOBALS['var2'];

    }

    // call the function

    getSum();

    // print the result stored in the global array

    echo "The sum is: " . $result;

?>

URLInPHP_1 

In the program stated above, two global variables, var1 and var2 are initialized with 2 integer values. The function getSum() stores the result of the addition of these two global variables in a GLOBAL array.

  • $_SERVER:

Server is a PHP superglobal that is defined as an array that contains the data about paths, headers, script location, etc. The web server itself makes these entries within the array. Using this to get full URL in PHP however depends on your server, as not every server provides that information. Some may skip them, whereas others may provide some extra data. The data provided by your web server is sometimes used to retrieve the data from a $_SERVER superglobal variable

The following program illustrates the $_SERVER variable in PHP.

<?php

    // print the name of the current file

    echo $_SERVER['PHP_SELF'];

    echo "<br>";

    // print the name of the server

    echo $_SERVER['SERVER_NAME'];

    echo "<br>";

    // print the name of the host

    echo $_SERVER['HTTP_HOST'];

    echo "<br>";

    // print the complete URL of the current page

    echo $_SERVER['HTTP_REFERER'];

    echo "<br>";

    // print the user agent string

    echo $_SERVER['HTTP_USER_AGENT'];

    echo "<br>";

    // print the path of the script

    echo $_SERVER['SCRIPT_NAME'];

?>

URLInPHP_2. 

In the program depicted above, various $_SERVER elements are used to retrieve information about the web page on the server. For example, $_SERVER['PHP_SELF'] is used to get the name of the current file, $_SERVER['SERVER_NAME'] is used to get the name of the server, $_SERVER['HTTP_HOST'] returns the name of the host, and so on.

  • $_REQUEST:

Request is another superglobal whose function is to collect and store the data whenever you submit an HTML form. This is one of the more common methods to get a full URL in PHP. The $_REQUEST[ ] array stores the information about $_GET, $_POST, and $_COOKIE by default. However, $_REQUEST is not in much use as the same purpose can be fulfilled by $_GET and $_POST.

The following program illustrates the $_REQUEST variable in PHP.

<!DOCTYPE html>

<html>

<body>

// create an HTML form 

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

    NAME: <input type="text" name="fname">

    <button type="submit">

        SUBMIT

    </button>

</form>

// PHP script using the $_REQUEST variable

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // $_REQUEST superglobal variable 

    // to request the name

    $name = htmlspecialchars($_REQUEST['fname']);

    if(empty($name)){

        echo "Enter Name";

    } else {

        echo $name;

    }

}

?>   

</body>

</html>

URLInPHP_3.

In the program mentioned above, you created an HTML form to get the username from the user. The $_REQUEST superglobal variable is used to retrieve the data and transfer it to the same page, using the ['PHP_SELF'], by clicking the submit button.

  • $_POST:

$_POST superglobal variable is used to retrieve the information from an HTML form after you submit it. The $_Post[ ] array is passed to the PHP script to store the data collected from the form. This method is highly secure from a security point of view since the query string does not reflect the data on submitting the form and is often considered a good way to get full URL in PHP.

The following program illustrates the $_POST variable in PHP.

<html>

<body> 

// create an HTML form

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

  Name: <input type="text" name="fname">

  <input type="submit">

</form> 

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") { 

  // read the input value

  $name = $_POST['fname']; 

  if (empty($name)) {

    echo "Enter name";

  } else {

    echo $name;

  }

}

?> 

</body>

</html>

URLInPHP_4 

In the above program, it creates an HTML form to get some data from the input field entered by the user. The $_POST is used to get the input data values and store these values in other variables, $name, and $age.

  • $_GET:

$_GET is a superglobal variable that is also used to retrieve the data from an HTML form after you submit it. It is an associative array of variables that are passed to your PHP script through URL parameters or query string.  This superglobal variable is quite opposite to the $_POST method as the query string reflects the data when you submit the form using $_GET.

The following piece of code illustrates the $_GET variable in PHP.

NOTE: The program is only for demonstration, and this piece of code can be embedded into an HTML code having a form, to get the user data entered in the form - in essence, modified as required to get full URL in PHP.

<?php 

    // get the data using $_GET

    $userName = $_GET['name'];

    $userAge = $_GET['age'];

    echo "<h1>This is ".$userName." of ".$userAge."</h1><br>";

?> 

In the example mentioned above, the $_GET superglobal variable is used to get the information entered by the user. This information is entered into an HTML form and the data is collected by the $_GET variable. This data will be visible in the URL as well.

  • $_FILES:

$_Files is an associative array that is used to store the items that are uploaded to the PHP script through the HTTP Post method.

The following program illustrates the $_FILES variable in PHP.

<!DOCTYPE html>

<html>

<body> 

// create an HTML form

<form action="test.php" method="POST" enctype="multipart/form-data">

   <input type="file" name="file">

   <input type ="submit" value="submit">

</form>

<?php

    // get the name of the file to be uploaded

    echo "Filename: " . $_FILES['file']['name']."<br>"; 

    // get the type of the file

    echo "Type : " . $_FILES['file']['type'] ."<br>";

    // get the size of the file

    echo "Size : " . $_FILES['file']['size'] ."<br>";

?> 

</body>

</html>

URLInPHP_5 

In the program depicted above, there is an HTML form with a button. When the button is clicked, it can upload a file. The details of the file which is uploaded, such as the file name, file type, and file size, are retrieved by using the $_FILES superglobal variable.

  • $_COOKIE:

$_COOKIE is used to store the values of PHP Cookies and can prove to be an alternative method to get full URL in PHP. Cookies are small text files that are used by various websites to get user information whenever they visit the site, such as username to personalize their page.

The following program illustrates the $_COOKIE variable in PHP.

<?php

    $setCookieName = "user";

    $setCookieValue = "testValue";

    // 86400 will be equal to 1 day

    setcookie($setCookieName, $setCookieValue, time() + (86400 * 30), "/");    

    if(!isset($_COOKIE[$setCookieName])) {

    echo "The cookie '" . $setCookieName . "' is not set!";

    } else {

    echo "The cookie '" . $setCookieName . "' is set!<br>";

    echo "And the value of the cookie is: " . $_COOKIE[$setCookieName];

    }

?>

URLInPHP_6

After reloading the website, you find that it will set the cookie.

URLInPHP_7.

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

Necessary Superglobal Variables

  • $_SERVER[‘HTTPS’]

$_SERVER[‘HTTPS’] is a necessary superglobal variable that gets set to a value other than NULL only if it has queried your PHP script via HTTPS protocol. In other words, you can say that if you have used HTTPS protocol on your existing web page, then this variable will return an “on”.

Syntax

<?php

    if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')

        echo "HTTPS";

    else

        echo "HTTP";

?>

URLInPHP_8

  • $_SERVER[‘HTTP_HOST’]

This superglobal variable is used to get the name of the webserver of the age on which you are currently active.

Syntax

 $domName = $_SERVER['HTTP_HOST'];

URLInPHP_9.

  • $_SERVER[‘REQUEST_URI’] 

$_SERVER[‘HTTP_HOST’] superglobal variable is used to get the name of the resource that you want to get.

Syntax

 $domName = $_SERVER['REQUEST_URI'];

URLInPHP_10

  • $_SERVER[‘SERVER_PORT’]

$_SERVER[‘SERVER_PORT’] superglobal variable is used to get the PORT number of your server machine that your web server is using. If you do not specify a PORT, this will be the default and consider the port number as ‘80’.

Syntax

 $domName = $_SERVER['SERVER_PORT'];

URLInPHP_11.

  • $_SERVER[‘QUERY_STRING’]

$_SERVER[‘QUERY_STRING’] superglobal variable is used to get the query string of your existing page, only if it is available in the URL link. 

Example 1:Display the URL of the Current Page Using a Conditional Statement

In this example, to get full URL in PHP, you divide the URL of any web page into a few parts: the protocol (HTTP or HTTPS), the domain name, and the URL of the resource location. In the program demonstrated below, you will retrieve the URL of the current page in three parts and finally combine them to get the complete URL.

The superglobal variables are used in this program. The variable $_SERVER[‘HTTP_HOST’] is used to read the domain name of the URL of the current web page. Store the returned domain name in a variable. The variable $_SERVER['REQUEST_URI'] returns the URI of the requested location of a resource. Store the returned value in a variable. The superglobal variable $_SERVER['HTTPS']  returns the protocol in the URL of a web page. To check whether the protocol of the current web page is HTTP or HTTPS, the conditional operator is used. First, the isset() method will check whether the superglobal variable $_SERVER['HTTPS'] is set or not. If the value returned by the superglobal variable is equal to “on”, then the protocol of the web page is HTTPS, otherwise, it is HTTP.

The following program demonstrates how to display the URL of the current page using the if-else statements:

<?php

    // get the name of the current page's domain

    $domName = $_SERVER['HTTP_HOST'];

    // get the uri of the requested location of the resource

    $sourceURI = $_SERVER['REQUEST_URI'];

    // get the https or http protocol of the url

    if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')

        $urlProtocol = "https";

    else

        $urlProtocol = "http";

    // now merge all variables storing the URL

    // address in parts

    $urlAddress = $urlProtocol."://".$domName.$sourceURI;

    // print the URL 

    echo "<h3 style='color:Red'>This is the URL address of the current

    page : </h3><br>";

    echo $urlAddress;

?> 

URLInPHP_12

Example 2: Display the URL of the Current Page Using the Ternary Operator

This example to get full URL in PHP is also based on the same approach discussed in the previous example. The only difference is that this time you use the ternary operator instead of using the traditional if-else statements.

The isset() method checks the protocol of the requested page, and if the value is set, and equals to “on”, then the ternary operator returns HTTPS, else it will return HTTP. The returned value is stored in a variable that is finally combined with all other parts of the URL retrieved in the program.

The following program shows how to display the URL of the current page using the ternary operator:

<?php

    // get the https or http protocol of the url

    $urlProtocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']

    == 'on' ? "https" : "http");

    // get the name of the current page's domain

    $domName = $_SERVER['HTTP_HOST'];

    //Read the requested resource

    // get the uri of the requested location of the resource

    $sourceURI = $_SERVER['REQUEST_URI'];

    // now merge all variables storing the URL

    // address in parts

    $urlAddress = $urlProtocol."://".$domName.$sourceURI;

    // print the URL 

    echo "<h3 style='color:Red'>This is the URL address of the current

    page : </h3><br>";

    echo $urlAddress;

?>

URLInPHP_13. 

Example 3: Display the URL of the Current Page Based on Port Number

In the previous approaches used to get full URL in PHP, you used $_SERVER[‘HTTPS’] to get the protocol of the URL of the current page without the query string. In the following example, you will see the use of the $_SERVER[‘SERVER_PORT’] superglobal variable to get the protocol along with the full URL and query string.

Unlike previous examples, you saw the use of various logical conditions to get the protocol. If $_SERVER[‘HTTPS’] is empty or isset to "off" then the program will check $_SERVER[‘SERVER_PORT’] to get the protocol of the URL of the current page. To find the query string, you used $_SERVER[‘QUERY_STRING’] superglobal variable.

The following program demonstrates how to display the URL of the current page using the port number:

<?php

// get the https or http protocol of the url

$getProtocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']

!= 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

// get the name of the current page's domain

$getDomain =  $_SERVER['HTTP_HOST'];

//Read the requested resource

    // get the uri of the requested location of the resource

$getResource = $_SERVER['REQUEST_URI'];

// get the value of the query string

$getQuery = $_SERVER['QUERY_STRING'];

// now append all variables storing the URL

    // address in parts

$getUrl = $getProtocol.$getDomain.$getResource;

// print the URL

echo "<h2 style='color:green'>This is the URL address of the current

    page : </h2>". $getUrl;

// print the query string

echo "<h3 style='color:Orange'>Printing the query string is : </h3>". $getQuery;

?>

URLInPHP_14

Learn Essential Skills for Effective Leadership

Executive Leadership Principles ProgramExplore Program
Learn Essential Skills for Effective Leadership

Conclusion

In this article, you saw how to access the full URL using a PHP script. You explored the superglobals in PHP and leveraged them to get the complete URL. This article then explored several examples such as displaying URLs using a conditional statement, using a ternary operator, and based on the port number as well. 

If you want to proceed beyond knowing how to get full URL in PHP, and start your comprehensive PHP learning journey, you can refer to this video as a guide. The online course on PHP Training will surely help you to learn PHP and you will be able to build dynamic web applications guided by industry experts. For PHP professionals, there is a specially designed Advanced PHP Development Training course that you can enroll in. This will allow you to learn advanced PHP concepts such as sessions, cookies, etc.

The next step that you can take is to learn MEAN stack development and give yourself a chance to work for top tech giants, check out our course on Post Graduate Program in Full Stack Web Development. In this course, you will learn some of the hottest skills like Node, Mongo, etc. that will help you to set your foot into professional web development. To get a complete list of free courses offered by Simplilearn, visit Free Courses.

If you have any questions for us regarding this “get full URL in PHP” article, please mention them in the comments section and we will have our experts answer them for you.

Happy Learning!