PHP Input Methods
Superglobals Overview
Section titled “Superglobals Overview”PHP automatically collects input data into special arrays called superglobals. These arrays are available everywhere in your script without any setup.
Think of superglobals as different mailboxes where PHP sorts incoming data based on how it arrived.
Key superglobals: $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_ENV
Choosing the Right Method
Section titled “Choosing the Right Method”Match the input method to your specific needs and security requirements.
1. GET Query String Parameters
Section titled “1. GET Query String Parameters”- Use for: Search queries, pagination, filters, shareable URLs
- Limitation: Visible in URL, size restricted, not secure for sensitive data
// URL: script.php?name=John&age=25
// Always check if parameter exists with fallback$name = $_GET['name'] ?? '';$age = $_GET['age'] ?? '0';
// For optional parameters, provide sensible defaults$page = $_GET['page'] ?? '1';$sort = $_GET['sort'] ?? 'newest';2. POST Data
Section titled “2. POST Data”- Use for: Form submissions, user registration, login, data modification
- Advantage: Hidden from URL, handles large amounts of data
// From HTML form with method="POST"$username = $_POST['username'] ?? '';$email = $_POST['email'] ?? '';
// Validate before usingif (!empty($username)) { echo htmlspecialchars($username);}3. Command Line Arguments
Section titled “3. Command Line Arguments”- Use for: Automation scripts, batch processing, system utilities
- Perfect for: Cron jobs and developer tools
// Command: php script.php file.txt backup$scriptName = $argv[0]; // "script.php"$filename = $argv[1] ?? null; // "file.txt"$action = $argv[2] ?? 'default'; // "backup"$argCount = $argc; // 3
// Always check if required arguments existif ($argc < 2) { echo "Usage: php script.php <filename> [action]\n"; exit(1);}4. File Uploads
Section titled “4. File Uploads”- Use for: User file uploads, attachments, documents
- Best practice: Implement security checks (size, type, location)
// HTML: <input type="file" name="document">$file = $_FILES['document'];
if ($file['error'] === UPLOAD_ERR_OK) { // Sanitize filename - remove path traversal and special characters $originalName = basename($file['name']); $safeName = preg_replace('/[^a-zA-Z0-9._-]/', '_', $originalName);
// Add unique prefix to prevent overwrites $finalName = uniqid() . '_' . $safeName;
move_uploaded_file($file['tmp_name'], "uploads/" . $finalName);}5. Cookies
Section titled “5. Cookies”- Use for: User preferences, shopping cart, remember settings
- Limitation: 4KB size limit, can be disabled by users
// Set cookie (before any output)setcookie('theme', 'dark', time() + 3600); // 1 hour
// Read cookie with fallback$theme = $_COOKIE['theme'] ?? 'light';6. Sessions
Section titled “6. Sessions”- Use for: User authentication, shopping carts, multi-step forms
- Advantage: Server-side storage, secure, larger data capacity
session_start(); // Always call first
// Store data$_SESSION['user_id'] = 123;$_SESSION['username'] = 'alice';
// Read dataif (isset($_SESSION['user_id'])) { echo "Welcome, " . htmlspecialchars($_SESSION['username']);}
// Logout - destroy the sessionsession_unset(); // Clear all session variablessession_destroy(); // Destroy the session7. Environment Variables
Section titled “7. Environment Variables”- Use for: Configuration, API keys, database credentials
- Best practice: Keep sensitive data out of source code
// getenv() - works everywhere, most reliable$apiKey = getenv('API_SECRET');
// $_ENV - requires variables_order to include "E" in php.ini$dbUrl = $_ENV['DATABASE_URL'] ?? '';
// $_SERVER - for server-specific variables$debug = $_SERVER['APP_DEBUG'] ?? 'false';8. Standard Input (STDIN)
Section titled “8. Standard Input (STDIN)”- Use for: Interactive CLI scripts, data processing pipelines
- Works with: Pipes (
echo "data" | php script.php) and file redirection
// Interactive command line inputecho "Enter your name: ";$name = trim(fgets(STDIN));
// Read piped data until end of file$allInput = stream_get_contents(STDIN);Security Essentials
Section titled “Security Essentials”Every external input is potentially dangerous until validated.
// 1. Validate input type and format$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
// 2. Escape output to prevent XSSecho htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// 3. Use prepared statements for database queries$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");$stmt->execute([$id]);Key principles:
- Never trust user input directly
- Validate type, length, and format
- Escape all output with
htmlspecialchars() - Use prepared statements for SQL
- Sanitize filenames for uploads