PHP Superglobals
Learn about PHP superglobals, their usage, and how they help in managing data.
What are Superglobals?
Superglobals are built-in global arrays in PHP that are always accessible, regardless of scope. They provide a way to access various types of data, including user input, session information, and server variables.
Types of Superglobals
PHP has several predefined superglobal arrays:
- $_GET: Collects data sent in the URL query string (HTTP GET method).
- $_POST: Collects data sent via HTML forms using the POST method.
- $_REQUEST: Collects data from both $_GET and $_POST (and $_COOKIE) combined.
- $_SESSION: Stores session variables, allowing data to persist across pages.
- $_COOKIE: Accesses cookies stored on the user's browser.
- $_SERVER: Provides information about the server and the current script, including headers and paths.
- $_FILES: Handles file uploads from forms.
- $_GLOBALS: Stores all global variables in an associative array.
Using Superglobals
$_GET Example
The $_GET
array is used to collect data from URL parameters:
<?php
// URL: yourpage.php?name=John&age=25
$name = $_GET['name']; // "John"
$age = $_GET['age']; // "25"
echo "Name: $name, Age: $age";
?>
$_POST Example
The $_POST
array is used to collect data from a form submission:
<form method="POST" action="yourpage.php">
Name: <input type="text" name="name">
<input type="submit">
</form>
<?php
$name = $_POST['name']; // Get the submitted name
echo "Hello, $name!";
?>
$_SESSION Example
Sessions are useful for maintaining user data across pages:
<?php
session_start(); // Start the session
$_SESSION['username'] = 'JohnDoe'; // Set a session variable
// Later on another page
session_start(); // Start the session again
echo $_SESSION['username']; // Outputs: JohnDoe
?>
$_SERVER Example
The $_SERVER
array contains information about the server and script:
<?php
echo $_SERVER['HTTP_USER_AGENT']; // Outputs the user's browser information
?>
$_FILES Example
To handle file uploads, use the $_FILES
superglobal:
<form method="POST" enctype="multipart/form-data">
Select file: <input type="file" name="myfile">
<input type="submit">
</form>
<?php
if (isset($_FILES['myfile'])) {
$file = $_FILES['myfile'];
echo "Uploaded file: " . $file['name']; // Outputs the name of the uploaded file
}
?>
Best Practices
Here are some best practices when working with superglobals:
- Always sanitize user input to prevent security vulnerabilities, such as SQL injection and XSS attacks.
- Use
isset()
to check if a superglobal variable is set before accessing it to avoid undefined index errors. - Start the session with
session_start()
before accessing or modifying session variables.
Conclusion
PHP superglobals are essential for handling data across various contexts in your application. Understanding how to use them effectively enhances your ability to build dynamic and secure web applications.