PHP Superglobals
PHP superglobals are built-in global arrays in PHP that provide access to various types of data throughout your application. They are available in all scopes and can be used to access or manipulate data like form inputs, session variables, cookies, and more. Here’s a rundown of the main PHP superglobals with examples:
-
$_GET
: Contains data sent via the URL query string (HTTP GET method).// URL: example.com/index.php?name=John&age=25 echo $_GET['name']; // Outputs: John echo $_GET['age']; // Outputs: 25
-
$_POST
: Contains data sent via the HTTP POST method (usually from forms).// Assume a form was submitted with a POST request echo $_POST['username']; // Outputs the value of the 'username' field echo $_POST['password']; // Outputs the value of the 'password' field
-
$_REQUEST
: Contains data from both$_GET
and$_POST
, and also$_COOKIE
.// Combining GET and POST data echo $_REQUEST['name']; // Outputs the 'name' value from GET or POST
-
$_SERVER
: Contains information about the server environment and HTTP headers.echo $_SERVER['HTTP_USER_AGENT']; // Outputs the user's browser information echo $_SERVER['REQUEST_METHOD']; // Outputs the request method (GET, POST, etc.)
-
$_SESSION
: Used to store session variables. Sessions must be started withsession_start()
before using$_SESSION
.session_start(); $_SESSION['username'] = 'JohnDoe'; echo $_SESSION['username']; // Outputs: JohnDoe
-
$_COOKIE
: Contains cookies sent by the client.// Set a cookie first setcookie('user', 'JohnDoe', time() + 3600); // Expires in 1 hour echo $_COOKIE['user']; // Outputs: JohnDoe (if cookie is set)
-
$_FILES
: Contains information about files uploaded through a form.// Assuming a form with file upload is submitted echo $_FILES['file']['name']; // Outputs the name of the uploaded file echo $_FILES['file']['size']; // Outputs the size of the uploaded file
-
$_ENV
: Contains environment variables.echo $_ENV['PATH']; // Outputs the system path environment variable
-
$_GLOBALS
: An associative array containing all global variables.$a = 10; function test() { global $a; echo $a; // Outputs: 10 } test();
These superglobals provide a way to access data across different parts of your PHP application, making it easier to handle form inputs, manage sessions, and interact with the server and environment.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.