PHP Superglobals
⏱ 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:
-
$_GLOBALS -
$_SERVER -
$_REQUEST -
$_POST -
$_GET -
$_FILES -
$_ENV -
$_COOKIE -
$_SESSION
$_GLOBALS
The $_GLOBALS array stores all global variables.
Example:
$_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:
$_REQUEST
Collects data from GET, POST, and COOKIE.
Example:
⚠️ Not recommended for secure applications.
$_GET
Collects form data sent using the GET method.
Example:
$_POST
Collects form data sent using the POST method.
Example:
$_FILES
Used to handle file uploads via forms.
Example:
$_ENV
Contains environment variables.
Example:
$_COOKIE
Stores data on the client browser.
Set Cookie:
Get Cookie:
$_SESSION
Stores session data on the server.
Example:
Comparison: GET vs POST
| Feature | GET | POST |
|---|---|---|
| Data visible | Yes | No |
| Data size | Limited | Unlimited |
| Security | Low | Higher |
| Use case | Search | Login, 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
$_POSTover$_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.
Register Now
Share this Post
← Back to Tutorials