PHP has several superglobals, including $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_SERVER, and $_ENV. Each serves a specific purpose in web development. Understanding these superglobals will allow you to manage user input, session data, and server information effectively.

Overview of PHP Superglobals

SuperglobalDescriptionUsage Example
$_GETUsed to collect data sent in the URL query string.$_GET['name'] retrieves the value of 'name' in the URL.
$_POSTUsed to collect data sent via HTTP POST method.$_POST['email'] retrieves the value of 'email' from a form submission.
$_SESSIONUsed to store session variables across pages.$_SESSION['user_id'] = 123; stores user ID in session.
$_COOKIEUsed to retrieve cookies set by the server.$_COOKIE['username'] retrieves the value of 'username' cookie.
$_FILESUsed to handle file uploads.$_FILES['file']['name'] retrieves the uploaded file name.
$_SERVERContains information about headers, paths, and script locations.$_SERVER['REQUEST_METHOD'] retrieves the request method (GET or POST).
$_ENVUsed to retrieve environment variables.$_ENV['PATH'] retrieves the system path variable.

Using $_GET and $_POST

Both $_GET and $_POST are essential for handling user input. The choice between them depends on the context of data submission.

Example: Using $_GET

When data is sent via the URL, it becomes part of the query string. For example, visiting example.com/index.php?name=John&age=30 allows you to access the values using $_GET.

// index.php
if (isset($_GET['name']) && isset($_GET['age'])) {
    $name = htmlspecialchars($_GET['name']);
    $age = (int)$_GET['age'];
    echo "Name: $name, Age: $age";
}

Example: Using $_POST

When submitting a form, you typically use the POST method to send data securely. Here's how to handle form submissions with $_POST.

// form.html
<form action="submit.php" method="POST">
    <input type="text" name="email" placeholder="Enter your email" required>
    <input type="submit" value="Submit">
</form>

// submit.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['email'])) {
        $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        echo "Email submitted: $email";
    }
}

Managing Sessions with $_SESSION

Sessions are crucial for maintaining user state across different pages. PHP provides the $_SESSION superglobal to store user data that persists throughout a user's visit.

Example: Starting a Session

To use sessions, you must start a session on each page where you want to access session variables.

// start_session.php
session_start();
$_SESSION['user_id'] = 123; // Store user ID
echo "Session started. User ID stored.";

Example: Accessing Session Data

You can access session data on any page after starting the session.

// access_session.php
session_start();
if (isset($_SESSION['user_id'])) {
    echo "User ID: " . $_SESSION['user_id'];
} else {
    echo "No user is logged in.";
}

Working with Cookies using $_COOKIE

Cookies allow you to store user data on the client side. The $_COOKIE superglobal retrieves this data.

Example: Setting and Retrieving Cookies

You can set a cookie using the setcookie() function and retrieve it using $_COOKIE.

// set_cookie.php
setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // 86400 = 1 day
echo "Cookie set for username.";

// access_cookie.php
if (isset($_COOKIE['username'])) {
    echo "Username from cookie: " . $_COOKIE['username'];
} else {
    echo "No username cookie found.";
}

Handling File Uploads with $_FILES

When users upload files through forms, PHP provides the $_FILES superglobal to manage these uploads.

Example: Handling File Uploads

Here's how to handle file uploads securely.

// upload.html
<form action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" required>
    <input type="submit" value="Upload">
</form>

// upload.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['file'])) {
        $fileName = $_FILES['file']['name'];
        $fileTmpName = $_FILES['file']['tmp_name'];
        $uploadDir = 'uploads/';

        if (move_uploaded_file($fileTmpName, $uploadDir . $fileName)) {
            echo "File uploaded successfully: $fileName";
        } else {
            echo "Failed to upload file.";
        }
    }
}

Conclusion

Understanding and effectively utilizing PHP superglobals is essential for building dynamic web applications. By leveraging $_GET, $_POST, $_SESSION, $_COOKIE, and $_FILES, you can handle user input, maintain sessions, manage cookies, and process file uploads efficiently. Always remember to sanitize and validate user input to ensure the security and integrity of your application.

Learn more with useful resources: