PHP Superglobals
Superglobals are built-in PHP variables that can be accessed from anywhere in your program.
Unlike normal variables, they do not require:
global
They are automatically available.
List of Superglobals
| Variable | Description |
|---|---|
| $_GET | URL Parameters |
| $_POST | Form Data |
| $_REQUEST | GET + POST + COOKIE |
| $_SERVER | Server Information |
| $_FILES | Uploaded Files |
| $_COOKIE | Browser Cookies |
| $_SESSION | User Sessions |
| $_ENV | Environment Variables |
| $GLOBALS | Global Variables |
$_GET
Retrieves data from URL.
Example:
https://example.com/index.php?id=10
PHP:
$id = $_GET["id"];
Output:
10
Checking Values Safely
Never do:
$id = $_GET["id"];
Because it may not exist.
Better:
$id =
$_GET["id"]
?? null;
Multiple Parameters
?name=Aayan&rank=Owner
PHP:
$name =
$_GET["name"];
$rank =
$_GET["rank"];
$_POST
Used in forms.
<form method="POST">
Example:
$username =
$_POST["username"];
Why POST?
POST data:
✅ Hidden from URL
✅ Supports large data
✅ Used for authentication
Example Login System
if (
isset($_POST["login"])
) {
$username =
$_POST["username"];
$password =
$_POST["password"];
}
$_REQUEST
Contains:
GET
POST
COOKIE
Example:
$name =
$_REQUEST["name"];
Usually avoid using this because it becomes unclear where data comes from.
$_SERVER
One of the most useful superglobals.
Contains:
- IP Address
- Request Method
- Host
- PHP Version
- User Agent
- Paths
Request Method
$_SERVER["REQUEST_METHOD"]
Output:
GET
POST
User Agent
$_SERVER["HTTP_USER_AGENT"]
IP Address
$_SERVER["REMOTE_ADDR"]
Current File
$_SERVER["PHP_SELF"]
Server Name
$_SERVER["SERVER_NAME"]
Request URI
$_SERVER["REQUEST_URI"]
Example API Router
$method =
$_SERVER["REQUEST_METHOD"];
switch ($method) {
case "GET":
break;
case "POST":
break;
}
$_FILES
Used for file uploads.
HTML:
<input type="file">
PHP:
$_FILES["image"];
Structure:
[
"name",
"tmp_name",
"size",
"error",
"type"
]
Upload Example
move_uploaded_file(
$_FILES["image"]["tmp_name"],
"uploads/image.png"
);
Security
Always validate:
mime_content_type()
Never trust file extensions.
$_COOKIE
Stores browser information.
Create:
setcookie(
"username",
"Aayan"
);
Read:
$_COOKIE["username"];
$_SESSION
Sessions store data on server.
Start session:
session_start();
Store:
$_SESSION["user"] =
"Aayan";
Read:
echo
$_SESSION["user"];
Destroy:
session_destroy();
Login Example
$_SESSION["logged"] =
true;
$_ENV
Environment Variables.
Example:
DB_HOST=127.0.0.1
DB_PASSWORD=secret
PHP:
$_ENV["DB_HOST"];
$GLOBALS
Contains every global variable.
Example:
$name = "Aayan";
echo
$GLOBALS["name"];
Security Best Practices
Never trust:
$_GET
$_POST
$_FILES
Always validate and sanitize.
Useful Functions
htmlspecialchars()
filter_var()
trim()
Exercises
- Create login form.
- Read GET parameters.
- Upload image.
- Store user session.
Real World Usage
Superglobals are used in:
- Laravel
- APIs
- CMS
- Authentication Systems
- Dashboards
- PocketMine Web Panels
- ZyroNetwork Panels
Next Chapter
➡ File Handling