Skip to content

PHP Input Methods

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


Match the input method to your specific needs and security requirements.


  • 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';

  • 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 using
if (!empty($username)) {
echo htmlspecialchars($username);
}

  • 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 exist
if ($argc < 2) {
echo "Usage: php script.php <filename> [action]\n";
exit(1);
}

  • 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);
}

  • 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';

  • 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 data
if (isset($_SESSION['user_id'])) {
echo "Welcome, " . htmlspecialchars($_SESSION['username']);
}
// Logout - destroy the session
session_unset(); // Clear all session variables
session_destroy(); // Destroy the session

  • 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';

  • Use for: Interactive CLI scripts, data processing pipelines
  • Works with: Pipes (echo "data" | php script.php) and file redirection
// Interactive command line input
echo "Enter your name: ";
$name = trim(fgets(STDIN));
// Read piped data until end of file
$allInput = stream_get_contents(STDIN);

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 XSS
echo 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