Superglobals in PHP
Superglobals in PHP
Superglobals in PHP are predefined variables that are always accessible in all scopes of a PHP script. They are used to collect data from forms, sessions, cookies, and server information.
What are Superglobals
Superglobals are built-in variables that can be accessed anywhere in your PHP code without needing to declare them as global. They play a key role in handling user input and server data.
Types of Superglobals in PHP
$GLOBALS
This superglobal is used to access global variables from anywhere in the script.
$x = 10;
$y = 20;
function add() {
$GLOBALS[‘z’] = $GLOBALS[‘x’] + $GLOBALS[‘y’];
}
add();
echo $z;
?>
$_GET
Used to collect data sent via URL parameters.
$name = $_GET[‘name’];
echo $name;
?>
$_POST
Used to collect data sent through forms using the POST method.
$name = $_POST[‘name’];
echo $name;
?>
$_REQUEST
Contains data from both GET and POST methods.
$name = $_REQUEST[‘name’];
echo $name;
?>
$_SERVER
Provides information about headers, paths, and script locations.
echo $_SERVER[‘SERVER_NAME’];
?>
$_SESSION
Used to store data across multiple pages.
session_start();
$_SESSION[‘user’] = “John”;
echo $_SESSION[‘user’];
?>
$_COOKIE
Used to store data on the user’s browser.
setcookie(“user”, “John”, time() + 3600);
echo $_COOKIE[‘user’];
?>
Why Superglobals are Important
Superglobals are essential for handling user input, managing sessions, and interacting with server data. They are widely used in form handling, authentication systems, and dynamic web applications.
Best Practices
Validate User Input
Always validate and sanitize data from $_GET and $_POST.
Use POST for Sensitive Data
Avoid sending sensitive data through URLs.
Manage Sessions Securely
Always use session management carefully to protect user data.
Start Your Learning Journey
Want to explore more courses like this? click here for free courses
FAQs – Superglobals in PHP
What are superglobals in PHP
Superglobals are predefined variables that can be accessed anywhere in a PHP script.
What is $_GET in PHP
It is used to collect data from URL parameters.
What is $_POST used for
It is used to collect form data securely.
What is $_SESSION
It stores user data across multiple pages.
What is $_SERVER
It provides server-related information.



