PHP Superglobals Variables

PHP Superglobal Variables: The Ultimate Guide for Beginners

Welcome to phponline.in, your go-to learning platform for beginner to advanced PHP tutorials. In this in-depth tutorial, we will dive into one of PHP’s most powerful and widely used features: Superglobal Variables.

By the end of this guide, you will fully understand what PHP Superglobals are, how they work, and how to use them securely and effectively in real-world applications.


What Are PHP Superglobal Variables?

Superglobals are built-in variables in PHP that are always accessible, regardless of scope. That means you can use them anywhere in your script — inside or outside of functions and classes — without needing to declare them as global.

They are automatically populated by the server or PHP engine and contain data from user input, server environment, cookies, sessions, and more.

List of Major PHP Superglobal Variables:

  1. $_GET
  2. $_POST
  3. $_REQUEST
  4. $_SERVER
  5. $_SESSION
  6. $_COOKIE
  7. $_FILES
  8. $_ENV
  9. $GLOBALS

Let’s explore each one in detail.


$_GET: Retrieve Data from the URL

The $_GET variable is used to collect data sent via URL parameters. It’s typically used with HTML forms with the method="get" attribute.

Example:

// URL: example.com/index.php?name=John
$name = $_GET['name'];
echo "Hello, $name!";

When to Use:

  • When bookmarking URLs
  • When sharing links
  • For simple search functionality

Note: Avoid using $_GET for sensitive data.


$_POST: Securely Collect Form Data

The $_POST variable is used to collect form data sent via HTTP POST method.

Example:

<form method="post">
  <input type="text" name="username">
  <input type="submit">
</form>

<?php
$username = $_POST['username'];
echo "Username: $username";
?>

When to Use:

  • When sending sensitive data (e.g., passwords)
  • When dealing with large datasets
  • When you don’t want data visible in the URL

$_REQUEST: Combined Access

$_REQUEST contains the content of $_GET, $_POST, and $_COOKIE. It is a general-purpose variable but should be used cautiously due to its broad scope.

Example:

$name = $_REQUEST['name'];
echo "Hello, $name!";

Tip:

Avoid using $_REQUEST when you need to strictly control data sources.


$_SERVER: Server and Execution Environment Info

The $_SERVER variable contains information about headers, paths, and script locations.

Common $_SERVER Elements:

echo $_SERVER['PHP_SELF'];
echo $_SERVER['SERVER_NAME'];
echo $_SERVER['HTTP_HOST'];
echo $_SERVER['REQUEST_METHOD'];
echo $_SERVER['REMOTE_ADDR'];

Use Cases:

  • Logging user IPs
  • Determining request methods
  • Getting script location

$_SESSION: Store Data Across Pages

The $_SESSION variable allows you to store user data across multiple pages. Sessions are started with session_start().

Example:

session_start();
$_SESSION['user'] = "John";
echo $_SESSION['user'];

Use Cases:

  • Login systems
  • Shopping carts
  • User preferences

Best Practices:

  • Always call session_start() before output
  • Regenerate session IDs to prevent hijacking

$_COOKIE: Store Data on User’s Computer

Cookies allow you to store data on the client-side.

Setting a Cookie:

setcookie("username", "John", time() + 3600); // 1 hour expiration

Accessing a Cookie:

echo $_COOKIE['username'];

Use Cases:

  • Auto-login
  • Storing user preferences
  • Tracking visitors

$_FILES: File Upload Management

This superglobal is used to handle file uploads.

Example:

<form method="post" enctype="multipart/form-data">
  <input type="file" name="myfile">
  <input type="submit">
</form>

<?php
$filename = $_FILES['myfile']['name'];
tmp_name = $_FILES['myfile']['tmp_name'];
move_uploaded_file($tmp_name, "uploads/$filename");
?>

Use Cases:

  • Uploading documents, images
  • Profile photo uploads

$_ENV: Environment Variables

The $_ENV array stores environment variables passed by the server.

Example:

echo $_ENV['PATH'];

Most servers do not populate this by default. Configuration may be required in php.ini or .htaccess.


 $GLOBALS: Access Global Variables

All global variables are stored in the $GLOBALS array.

Example:

$x = 10;
$y = 20;

function sum() {
  $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
sum();
echo $z;

Use $GLOBALS sparingly to avoid code complexity.


Security Tips When Using Superglobals

  • Always sanitize user input: Use htmlspecialchars(), filter_input()
  • Use prepared statements for database queries
  • Validate file types and sizes for uploads
  • Regenerate session IDs regularly
  • Set secure and HttpOnly flags on cookies

Real-World Use Case: Login System with $_POST and $_SESSION

session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $username = $_POST['username'];
  $password = $_POST['password'];
  // Check credentials
  if ($username == "admin" && $password == "123") {
    $_SESSION['loggedin'] = true;
    echo "Welcome, admin!";
  } else {
    echo "Invalid credentials";
  }
}

PHP superglobals, PHP $_GET, PHP $_POST, PHP $_SESSION, PHP $_COOKIE, PHP $_SERVER, PHP $_FILES, PHP global variables, PHP tutorial for beginners

Related Topics


Frequently Asked Questions (FAQ)

What are PHP Superglobals?

They are built-in variables in PHP accessible globally, including $_GET, $_POST, $_SESSION, etc.

Which is safer: $_GET or $_POST?

$_POST is safer as the data is not visible in the URL and supports larger data sizes.

How to start a PHP session?

Use session_start() at the beginning of the script before any output.

Can cookies be modified by users?

Yes. That’s why sensitive data should never be stored in cookies.

What’s the purpose of $_FILES?

It manages file uploads via HTTP POST.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments