Skip to content

PHP Superglobals

Superglobals are built-in variables that are always available in all scopes throughout a PHP script. They are arrays that contain information from various sources and are accessible from any function, class, or file without the need for the global keyword.

The $_GET superglobal is an associative array of variables passed to the current script via the URL parameters (query string).

Basic Usage:

<?php
// URL: http://example.com/page.php?id=123&name=John
// Access GET parameters
$user_id = $_GET['id']; // 123
$user_name = $_GET['name']; // "John"
echo "User ID: " . $user_id . "<br>";
echo "User Name: " . $user_name;
// Check if parameter exists
if (isset($_GET['search'])) {
$search_term = $_GET['search'];
echo "Searching for: " . htmlspecialchars($search_term);
}

Security Considerations:

<?php
// Always validate and sanitize GET data
$id = isset($_GET['id']) ? intval($_GET['id']) : 0; // Convert to integer
$name = isset($_GET['name']) ? htmlspecialchars($_GET['name']) : ''; // Prevent XSS
// For string parameters, use filter_input
$email = filter_input(INPUT_GET, 'email', FILTER_SANITIZE_EMAIL);
// Better practice: validate before use
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = (int)$_GET['id'];
// Proceed with valid id
} else {
// Handle error
die("Invalid ID parameter");
}

Example Form: HTML

form.html
<form action="process.php" method="get">
<input type="text" name="search" placeholder="Search...">
<select name="category">
<option value="books">Books</option>
<option value="movies">Movies</option>
</select>
<input type="submit" value="Search">
</form>

PHP

Last login: " . date('Y-m-d H:i:s', $_SESSION['last_login']); // logout.php session_start(); session_unset(); // Remove all session variables session_destroy(); // Destroy the session setcookie(session_name(), '', time() - 3600); // Delete session cookie header('Location: login.php'); exit; ``` **Session Security Tips:** ```php 1800) { // 30 minutes session_regenerate_id(true); $_SESSION['created'] = time(); } // Store user agent for verification if (!isset($_SESSION['user_agent'])) { $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT']; } elseif ($_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) { // Possible session hijacking session_destroy(); die("Security violation detected"); } ``` ### 5. $\_COOKIE The $\_COOKIE superglobal contains variables passed to the current script via HTTP cookies. **Basic Usage:** ```php 'dark', 'language' => 'en']), [ 'expires' => time() + (86400 * 365), 'path' => '/', 'domain' => 'example.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Strict' ] ); // Delete a cookie setcookie("user", "", time() - 3600, "/"); ``` **Example: Remember Me Functionality:** ```php storeToken($user_id, $token, $expiry); setcookie( "remember_me", $token, [ 'expires' => $expiry, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'Strict' ] ); } // Check remember me cookie function checkRememberMe() { if (isset($_COOKIE['remember_me'])) { $token = $_COOKIE['remember_me']; // Verify token in database // $user_id = $db->verifyToken($token); if ($user_id) { // Log user in automatically $_SESSION['user_id'] = $user_id; return true; } } return false; } ``` ### 6. $\_SERVER The $\_SERVER superglobal contains information about the server and execution environment. **Common $\_SERVER Elements:** ```php "; echo "Server Name: " . $_SERVER['SERVER_NAME'] . "
"; echo "Server Software: " . $_SERVER['SERVER_SOFTWARE'] . "
"; echo "Server Protocol: " . $_SERVER['SERVER_PROTOCOL'] . "
"; echo "Server Port: " . $_SERVER['SERVER_PORT'] . "

"; echo "Request Information:
"; echo "Request Method: " . $_SERVER['REQUEST_METHOD'] . "
"; echo "Request URI: " . $_SERVER['REQUEST_URI'] . "
"; echo "Query String: " . $_SERVER['QUERY_STRING'] . "
"; echo "Script Name: " . $_SERVER['SCRIPT_NAME'] . "
"; echo "Script Filename: " . $_SERVER['SCRIPT_FILENAME'] . "

"; echo "Client Information:
"; echo "Remote Address: " . $_SERVER['REMOTE_ADDR'] . "
"; echo "Remote Port: " . $_SERVER['REMOTE_PORT'] . "
"; echo "User Agent: " . $_SERVER['HTTP_USER_AGENT'] . "
"; echo "Accept Language: " . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . "

"; echo "Other Useful Elements:
"; echo "Document Root: " . $_SERVER['DOCUMENT_ROOT'] . "
"; echo "HTTPS: " . (isset($_SERVER['HTTPS']) ? 'Yes' : 'No') . "
"; echo "HTTP Host: " . $_SERVER['HTTP_HOST'] . "
"; echo "HTTP Referer: " . ($_SERVER['HTTP_REFERER'] ?? 'Not set') . "
"; ``` **Practical Examples:** ```php "; echo "Path: " . ($_ENV['PATH'] ?? 'Not set') . "
"; echo "Temporary Directory: " . ($_ENV['TMPDIR'] ?? sys_get_temp_dir()) . "
"; ``` **Using .env Files (with vlucas/phpdotenv):** ```php load(); // Now access via getenv() or $_ENV $db_host = $_ENV['DB_HOST']; $api_key = $_ENV['API_KEY']; // Or using getenv() $debug = getenv('APP_DEBUG') === 'true'; // Required variables $dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']); ``` ### 8. $\_FILES The $\_FILES superglobal contains items uploaded via HTTP POST method with enctype="multipart/form-data". **Basic Structure of $\_FILES:** ```php Array ( [avatar] => Array ( [name] => photo.jpg [type] => image/jpeg [tmp_name] => /tmp/php/php6hst32 [error] => 0 [size] => 98174 ) ) ``` **_File Upload Example:_** php ```php $max_size) { die("File is too large. Maximum size is 2MB."); } // Validate file extension $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif']; if (!in_array($extension, $allowed_extensions)) { die("Invalid file extension."); } // Generate unique filename $new_filename = uniqid() . '.' . $extension; $upload_path = __DIR__ . '/uploads/' . $new_filename; // Move uploaded file if (move_uploaded_file($file['tmp_name'], $upload_path)) { echo "File uploaded successfully!"; echo "
Saved as: " . htmlspecialchars($new_filename); } else { die("Failed to move uploaded file."); } }
``` **Multiple File Upload:** ```php $error) { if ($error === UPLOAD_ERR_OK) { $tmp_name = $files['tmp_name'][$key]; $name = basename($files['name'][$key]); $upload_path = __DIR__ . '/uploads/' . $name; if (move_uploaded_file($tmp_name, $upload_path)) { $uploaded_files[] = $name; } } } echo "Uploaded " . count($uploaded_files) . " files."; }
``` **File Upload Security Tips:** ```php 5 * 1024 * 1024, // 5MB 'allowed_types' => ['image/jpeg', 'image/png'], 'upload_dir' => __DIR__ . '/uploads/', 'rename' => true ]; $options = array_merge($defaults, $options); if (!isset($_FILES[$field_name])) { return ['error' => 'No file uploaded']; } $file = $_FILES[$field_name]; // Check upload errors if ($file['error'] !== UPLOAD_ERR_OK) { return ['error' => 'Upload failed: ' . $file['error']]; } // Check file size if ($file['size'] > $options['max_size']) { return ['error' => 'File too large']; } // Verify MIME type using finfo (more reliable than $_FILES['type']) $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime_type = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo); if (!in_array($mime_type, $options['allowed_types'])) { return ['error' => 'Invalid file type: ' . $mime_type]; } // Get safe filename $extension = pathinfo($file['name'], PATHINFO_EXTENSION); $safe_extension = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $extension)); if ($options['rename']) { $new_filename = uniqid() . '.' . $safe_extension; } else { $new_filename = preg_replace('/[^a-zA-Z0-9\._-]/', '', $file['name']); } $destination = $options['upload_dir'] . $new_filename; // Ensure upload directory exists if (!is_dir($options['upload_dir'])) { mkdir($options['upload_dir'], 0755, true); } // Move file if (move_uploaded_file($file['tmp_name'], $destination)) { return [ 'success' => true, 'filename' => $new_filename, 'path' => $destination, 'size' => $file['size'], 'type' => $mime_type ]; } return ['error' => 'Failed to save file']; } ``` Security Considerations for All Superglobals General Security Rules: Never trust user input - Always validate and sanitize Use prepared statements for database queries Escape output with htmlspecialchars() when displaying user data Validate data types and ranges Use HTTPS for sensitive data transmission **Input Validation Example:** ```php ['min_range' => $min, 'max_range' => $max] ]); return $filtered !== false ? $filtered : false; case 'url': return filter_var($input, FILTER_VALIDATE_URL); case 'string': default: $input = trim($input); $max_length = $options['max_length'] ?? 255; if (strlen($input) > $max_length) { return false; } return htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); } } // Usage $clean_email = validateInput($_POST['email'], 'email'); $clean_age = validateInput($_POST['age'], 'int', ['min' => 1, 'max' => 120]); $clean_name = validateInput($_POST['name'], 'string', ['max_length' => 100]); ``` **Remember**: Superglobals are powerful tools, but with great power comes great responsibility. Always validate, sanitize, and secure your data handling.