</>
Skip to content
PHP lessons (23/49)

PHP — Forms

GET method

<!-- form.html -->
<form action="process.php" method="GET">
    <input type="text" name="name">
    <input type="email" name="email">
    <button type="submit">Submit</button>
</form>
<?php
// process.php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $name = htmlspecialchars($_GET['name'] ?? '');
    $email = htmlspecialchars($_GET['email'] ?? '');

    echo "Name: $name, Email: $email";
}
?>

POST method

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = htmlspecialchars($_POST['name'] ?? '');
    $email = htmlspecialchars($_POST['email'] ?? '');

    // Validate
    $errors = [];
    if (empty($name)) $errors[] = "Name is required";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email";
    }

    if (empty($errors)) {
        // Process form
        echo "Form submitted successfully!";
    } else {
        foreach ($errors as $error) {
            echo "<p>$error</p>";
        }
    }
}
?>

File upload

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file = $_FILES['avatar'];

    // Check for errors
    if ($file['error'] === UPLOAD_ERR_OK) {
        $allowed = ['image/jpeg', 'image/png', 'image/gif'];

        if (in_array($file['type'], $allowed)) {
            $newName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            move_uploaded_file($file['tmp_name'], "uploads/$newName");
            echo "File uploaded: $newName";
        } else {
            echo "Invalid file type";
        }
    }
}
?>

CSRF protection

<?php
session_start();

// Generate token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

<form method="POST">
    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
    <!-- form fields -->
</form>

<?php
// Validate token
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die("Invalid CSRF token");
}
?>

Mini Practice

Write PHP code that:

  1. Processes a GET form
  2. Validates POST form data
  3. Handles file uploads
  4. Implements CSRF protection

Up Next

In the next lesson, you'll learn about Database — connecting to databases with PHP.

Related Topics

Frequently Asked Questions about Forms

What is Forms in PHP?

Forms is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Forms?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Forms.

Why is Forms important in PHP?

Forms is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.