Superglobals in PHP

Superglobals in PHP

Understanding predefined global variables in PHP.

Superglobals in PHP

Superglobals in PHP are predefined variables that are always accessible, regardless of scope. They provide easy access to global data like form inputs, session information, server details, and more. Here's an explanation of each superglobal with examples:

1. $_GET

Description: Used to collect data sent via the HTTP GET method. Data is appended to the URL and is visible in the browser's address bar.

Use Case: Passing data via URL parameters, such as search queries or pagination.

// URL: example.com/index.php?name=John&age=25

$name = $_GET['name']; // "John"
$age = $_GET['age'];   // "25"

echo "Name: " . $name . "<br>";
echo "Age: " . $age;
            

Output:

Name: John
Age: 25
            

2. $_POST

Description: Used to collect data sent via the HTTP POST method. This data is not visible in the URL and is typically used for form submissions.

Use Case: Submitting form data, such as login credentials or file uploads.

// HTML Form (in index.php)
<form method="post" action="submit.php">
    Name: <input type="text" name="name">
    Age: <input type="text" name="age">
    <input type="submit" value="Submit">
</form>

// PHP Script (in submit.php)
$name = $_POST['name'];
$age = $_POST['age'];

echo "Name: " . $name . "<br>";
echo "Age: " . $age;
            

Output (after submitting the form):

Name: [User's Input]
Age: [User's Input]
            

3. $_SERVER

Description: Contains information about the server environment and the current request.

Use Case: Accessing server-specific data, such as headers, script locations, and request methods.

echo "Server Name: " . $_SERVER['SERVER_NAME'] . "<br>";
echo "Request Method: " . $_SERVER['REQUEST_METHOD'] . "<br>";
echo "Script Name: " . $_SERVER['SCRIPT_NAME'] . "<br>";
echo "Client IP: " . $_SERVER['REMOTE_ADDR'];
            

Output:

Server Name: example.com
Request Method: GET
Script Name: /index.php
Client IP: 192.168.1.1
            

4. $_SESSION

Description: Used to store and persist user data across different pages during a session. Requires session management to be initiated with session_start().

Use Case: Storing user data like login status, user ID, or shopping cart items.

// Start the session
session_start();

// Store session data
$_SESSION['username'] = 'JohnDoe';

// Access session data
echo "Username: " . $_SESSION['username'];
            

Output:

Username: JohnDoe
            

5. $_COOKIE

Description: Used to store data on the client side, which can be accessed in subsequent requests. Cookies are stored as key-value pairs in the user's browser.

Use Case: Remembering user preferences, login states, or tracking user activity.

// Set a cookie
setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // 86400 = 1 day

// Access the cookie
if(isset($_COOKIE['username'])) {
    echo "Username: " . $_COOKIE['username'];
} else {
    echo "Cookie 'username' is not set!";
}
            

Output:

Username: JohnDoe
            

6. $_FILES

Description: Used to handle file uploads via an HTML form. Contains information about the uploaded file, such as name, type, size, and temporary location.

Use Case: Handling user file uploads, such as profile pictures or documents.

// HTML Form
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

// PHP Script (in upload.php)
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
            

Output (after file upload):

The file [filename] has been uploaded.
            

7. $_REQUEST

Description: A general-purpose superglobal that can hold data from $_GET, $_POST, and $_COOKIE. It’s not commonly used due to potential security risks.

Use Case: Accessing data from both GET and POST methods, though it's better to use $_GET or $_POST directly for clarity and security.

// URL: example.com/index.php?name=John
// Or via POST form with method="post"

$name = $_REQUEST['name'];
echo "Name: " . $name;
            

Output:

Name: John
            
Previous Next
Modern Footer