PHP Global Variables - Superglobals

In PHP, superglobals are built-in global arrays that are always accessible, regardless of scope — you can access them from any function, class, or file without needing to use global or other special mechanisms.

Here are the main PHP superglobals:


1. $_GLOBALS

  • An associative array that contains all global variables.

  • Useful for accessing global variables from within functions.

$x = 10; $y = 20; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; // 30

2. $_SERVER

  • Contains information about headers, paths, and script locations.

  • Common entries:

    • $_SERVER['PHP_SELF']: The filename of the currently executing script.

    • $_SERVER['SERVER_NAME']

    • $_SERVER['REQUEST_METHOD']

echo $_SERVER['PHP_SELF']; // Outputs the current file path

3. $_REQUEST

  • Collects data after submitting an HTML form with either GET or POST.

  • Also includes COOKIE data.

$name = $_REQUEST['username'];

4. $_POST

  • Collects data submitted via HTTP POST method.

  • Secure for handling sensitive data (e.g., passwords).

$name = $_POST['username'];

5. $_GET

  • Collects data sent in the URL via HTTP GET.

  • Less secure; used for non-sensitive data like search queries.

echo $_GET['id'];

6. $_FILES

  • Handles file uploads.

$_FILES['uploadedFile']['name']; // Original name of the uploaded file

7. $_ENV

  • Contains environment variables passed to the script.

echo $_ENV['PATH'];

8. $_COOKIE

  • Contains cookies sent to the script.

$cookie_value = $_COOKIE['user'];

9. $_SESSION

  • Used to store session variables across multiple pages.

session_start(); $_SESSION['favcolor'] = 'green';