PHP Superglobals

📘 PHP 👁 37 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

What are Superglobals in PHP?

PHP Superglobals are built-in global arrays that are always accessible, regardless of scope. You can use them inside functions, classes, or files without declaring them as global.


List of PHP Superglobals

PHP provides the following main superglobal variables:

  1. $_GLOBALS

  2. $_SERVER

  3. $_REQUEST

  4. $_POST

  5. $_GET

  6. $_FILES

  7. $_ENV

  8. $_COOKIE

  9. $_SESSION


$_GLOBALS

The $_GLOBALS array stores all global variables.

Example:

<?php $x = 10; $y = 20; function sum() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } sum(); echo $z; ?>

$_SERVER

Contains server and execution environment information.

Common Elements:

  • $_SERVER['PHP_SELF']

  • $_SERVER['SERVER_NAME']

  • $_SERVER['REQUEST_METHOD']

  • $_SERVER['HTTP_USER_AGENT']

  • $_SERVER['REMOTE_ADDR']

Example:

<?php echo $_SERVER['SERVER_NAME']; ?>

$_REQUEST

Collects data from GET, POST, and COOKIE.

Example:

<?php echo $_REQUEST['username']; ?>

⚠️ Not recommended for secure applications.


$_GET

Collects form data sent using the GET method.

Example:

<?php echo $_GET['name']; ?>

$_POST

Collects form data sent using the POST method.

Example:

<?php echo $_POST['email']; ?>

$_FILES

Used to handle file uploads via forms.

Example:

<?php echo $_FILES['file']['name']; ?>

$_ENV

Contains environment variables.

Example:

<?php echo $_ENV['PATH']; ?>

$_COOKIE

Stores data on the client browser.

Set Cookie:

setcookie("user", "Admin", time() + 3600);

Get Cookie:

echo $_COOKIE['user'];

$_SESSION

Stores session data on the server.

Example:

<?php session_start(); $_SESSION['username'] = "Admin"; echo $_SESSION['username']; ?>

Comparison: GET vs POST

FeatureGETPOST
Data visibleYesNo
Data sizeLimitedUnlimited
SecurityLowHigher
Use caseSearchLogin, Forms

Security Tips for Superglobals

  • Always validate user input

  • Sanitize data before output

  • Use filter_input() where possible

  • Avoid trusting user input blindly

  • Use prepared statements for database queries


Best Practices

  • Prefer $_POST over $_REQUEST

  • Escape output using htmlspecialchars()

  • Validate file uploads using $_FILES

  • Use sessions for sensitive data


Conclusion

PHP superglobals play a crucial role in handling user input, server data, sessions, and cookies. Understanding them is essential for building secure and dynamic PHP applications.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes