PHP Global Variables ( Superglobals)

In PHP, global variables are variables that can be accessed from anywhere in the code, including within functions and classes. However, to use a global variable inside a function, you need to use the global keyword to specify the variable name.

In addition to regular global variables, PHP also has a set of built-in global variables called Superglobals. These are predefined variables that are always available in all scopes throughout a script. They start with an underscore followed by an uppercase letter and are always in uppercase.

Here are some of the most commonly used Superglobals and their descriptions:

  1. $_SERVER – Contains information about the current script and server environment.
  2. $_GET – Contains variables passed to the current script via the URL parameters.
  3. $_POST – Contains variables passed to the current script via HTTP POST method.
  4. $_REQUEST – Contains the contents of $_GET, $_POST and $_COOKIE.
  5. $_SESSION – Contains session variables available to the current script.

Here are some code examples to demonstrate the usage of Superglobals:

  1. Using $_SERVER to get the current URL:
$current_url = $_SERVER['REQUEST_URI'];
echo $current_url;

In this example, the $_SERVER Superglobal is used to get the current URL of the script. The REQUEST_URI element of the $_SERVER array contains the current request URL. The variable $current_url is assigned the value of the REQUEST_URI element and then printed to the screen using the echo statement.

  1. Using $_GET to get data from a form:
<form action="process.php" method="get">
  <input type="text" name="name">
  <input type="submit" value="Submit">
</form>
<?php
if(isset($_GET['name'])) {
  $name = $_GET['name'];
  echo "Hello " . $name;
}
?>

In this example, the $_GET Superglobal is used to get data from a form. When the form is submitted, the data is sent to the process.php script using the GET method. The if statement checks if the name parameter is set in the URL, and if it is, the $name variable is assigned the value of the name parameter and then printed to the screen using the echo statement.

  1. Using $_SESSION to set and get session data:
session_start();
$_SESSION['name'] = 'John';
echo $_SESSION['name'];

In this example, the session_start() function is used to start a new session, and then the $_SESSION Superglobal is used to set a session variable named name with the value 'John'. The value of the name session variable is then printed to the screen using the echo statement.

By using Superglobals in PHP, you can easily access and manipulate global variables without having to pass them as function arguments or class properties. This makes it easier to work with data across different parts of your code.