Web Development
HTML Course
CSS Course
JavaScript Course
PHP Course
Python Course
SQL Course
SEO Course

Forms in PHP & User Input

HTML forms allow users to send data to the server. In PHP, this data is received and processed to create dynamic pages, store information in databases, or interact with web applications. Before diving into technical details, we need to understand the two main methods for sending data: GET and POST.

What is the GET method?

The GET method sends form data through the URL. This means the information appears in the browser's address bar as key=value pairs, separated by the & symbol. GET is usually used for actions that do not modify server data, such as searches or filtering a product catalog.

GET Advantages and Disadvantages

Simple GET Example

<!DOCTYPE html>
<html>
<body>

<form action="result.php" method="get">
  Name: <input type="text" name="name"><br>
  Age: <input type="number" name="age"><br>
  <input type="submit" value="Submit">
</form>

</body>
</html>

What is the POST method?

The POST method sends data in the body of the HTTP request, not in the URL. This allows sending larger amounts of data and is safer for sensitive information, such as passwords or private messages. POST is used for actions that modify server data, such as user registration or submitting a contact form.

Simple POST Example

<!DOCTYPE html>
<html>
<body>

<form action="result.php" method="post">
  Email: <input type="email" name="email"><br>
  Password: <input type="password" name="password"><br>
  <input type="submit" value="Submit">
</form>

</body>
</html>

POST Advantages and Disadvantages

Now that we understand the basic concepts of GET and POST methods, we can move on to how PHP retrieves this data using the superglobals $_GET and $_POST.

PHP Superglobals for Forms

In PHP, data sent through forms is not accessible directly as normal variables. They are available through superglobals, which are predefined, global variables accessible in any context of the script. The most important ones for forms are:

$_GET

A superglobal that stores data sent via the GET method. It is an associative array where the key is the name of the form field and the value is what the user entered.

Example

<?php
// URL: form.php?name=John&varsta=30
echo "The name is: " . $_GET['name'];   // outputs: The name is: John
echo "The age is: " . $_GET['varsta']; // outputs: The age is: 30
?>

$_POST

A superglobal that stores data sent via the POST method. It is also an associative array with the key as the field name and the value entered by the user. POST is safer than GET for sensitive data and can carry more information.

Example

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    echo "Hello, $name! I received the email: $email";
}
?>

$_REQUEST

A superglobal that combines data from $_GET, $_POST, and $_COOKIE. It is less recommended for large projects, as it can be harder to control exactly where the data comes from.

$_SERVER

A superglobal that provides information about the server and the current HTTP request. For example, we can check the method used (GET or POST) or the address of the current script.

Example: checking the form method

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "The form was submitted via POST!";
} else {
    echo "The form has not been submitted yet.";
}
?>

Data sanitization in PHP

When users submit data through forms, we cannot trust that this data is safe. A malicious user could send HTML, JavaScript, or other harmful code. That's why we must sanitize the data before using or displaying it.

The htmlspecialchars() function

Converts special HTML characters into safe entities. This way, any HTML code entered by the user will not be executed, but displayed as plain text.

Example with htmlspecialchars()

<?php
$input = '<script>alert("Hacked!")</script>';
$safeInput = htmlspecialchars($input);

echo $safeInput;
// Output: <script>alert("Hacked!")</script>
?>

The filter_var() function

A more flexible way to validate and sanitize data. It has different filters, such as for email, URL, or numbers.

Example: email validation

<?php
$email = "user@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email: $email";
} else {
    echo "Invalid email!";
}
?>

Example: string sanitization

<?php
$input = " <b>Hello!</b> ";
$sanitized = filter_var($input, FILTER_SANITIZE_STRING);
echo $sanitized; // Output: Hello!
?>

Validating required fields

It is important to check whether the user has filled in all required fields. If a required field is empty, we should display an error message and not process the data.

Simple validation example

<?php
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']); // remove spaces at the beginning and end
    $email = trim($_POST['email']);

    if (empty($name)) {
        $errors[] = "The Name field is required.";
    }

    if (empty($email)) {
        $errors[] = "The Email field is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "The email address is not valid.";
    }

    if (empty($errors)) {
        echo "Data is valid! Name: $name, Email: $email";
    } else {
        foreach ($errors as $error) {
            echo "<p style='color:red;'>$error</p>";
        }
    }
}
?>

Submitting and displaying data on a new page

When a user fills out a form, we can submit the data to the same page or to a different page. In this example, we will send the data to a new page called rezultat.php.

HTML Form

<form action="rezultat.php" method="post">
    <label for="name">Name:</label>
    <input type="text" name="name" id="name" required><br><br>

    <label for="email">Email:</label>
    <input type="email" name="email" id="email" required><br><br>

    <input type="submit" value="Submit">
</form>

Page rezultat.php

<?php
// Receive form data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);

echo "<p>Hello, $name!</p>";
echo "<p>Your email is: $email</p>";
?>

Note: we use htmlspecialchars() to prevent HTML or JavaScript injection.

File upload with $_FILES

PHP allows us to handle files uploaded by users via forms. The form must have the attribute enctype="multipart/form-data".

File upload form

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="fisier">Choose file:</label>
    <input type="file" name="fisier" id="fisier" required><br><br>

    <input type="submit" value="Upload">
</form>

Page upload.php

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['fisier']) && $_FILES['fisier']['error'] === 0) {
        $nameFisier = $_FILES['fisier']['name'];
        $tmpLocatie = $_FILES['fisier']['tmp_name'];
        $folderDestinatie = 'uploads/' . $nameFisier;

        // Move the file to the uploads folder
        if (move_uploaded_file($tmpLocatie, $folderDestinatie)) {
            echo "<p>File $nameFisier uploaded successfully!</p>";
        } else {
            echo "<p style='color:red;'>An error occurred during upload.</p>";
        }
    } else {
        echo "<p style='color:red;'>No file selected or an error occurred.</p>";
    }
}
?>

Important notes

Complete contact form in PHP

This example combines everything we've discussed: user input, validation, POST submission, and displaying data on the result page.

contact.php - The Form

<?php
// If data was previously submitted, we can keep it in the form to avoid retyping
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$message = $_POST['mesaj'] ?? '';
$error = '';
?>

<form action="contact-rezultat.php" method="post">
    <label for="name">Name:</label>
    <input type="text" name="name" id="name" value="<?php echo htmlspecialchars($name); ?>" required><br><br>

    <label for="email">Email:</label>
    <input type="email" name="email" id="email" value="<?php echo htmlspecialchars($email); ?>" required><br><br>

    <label for="mesaj">Message:</label><br>
    <textarea name="mesaj" id="mesaj" rows="5" required><?php echo htmlspecialchars($message); ?></textarea><br><br>

    <input type="submit" value="Send">
</form>

<?php
if ($error) {
    echo "<p style='color:red;'>$error</p>";
}
?>

contact-rezultat.php - Processing and Display

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve and sanitize the data
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);
    $message = htmlspecialchars($_POST['mesaj']);

    // Simple validations
    $errors = [];
    if (empty($name)) $errors[] = "Name is required.";
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "A valid email is required.";
    if (empty($message)) $errors[] = "Message cannot be empty.";

    if (!empty($errors)) {
        echo "<p style='color:red;'>Errors occurred:</p>";
        echo "<ul style='color:red;'>";
        foreach ($errors as $e) {
            echo "<li>$e</li>";
        }
        echo "</ul>";
        echo "<a href='contact.php'>Back to the form</a>";
        exit;
    }

    // Display data if everything is correct
    echo "<h3>Message sent successfully!</h3>";
    echo "<p><strong>Name:</strong> $name</p>";
    echo "<p><strong>Email:</strong> $email</p>";
    echo "<p><strong>Message:</strong><br>$message</p>";
} else {
    echo "<p style='color:red;'>Direct access to this page is not allowed.</p>";
}
?>

Additional explanations

🔧 PHP Example:
<?php
// Simple example of form and processing
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = htmlspecialchars($_POST['name'] ?? '');
    $email = htmlspecialchars($_POST['email'] ?? '');
    $message = htmlspecialchars($_POST['message'] ?? '');
    echo "<h3>Message received!</h3>";
    echo "<p>Name: $name</p>";
    echo "<p>Email: $email</p>";
    echo "<p>Message: $message</p>";
} else {
?>
<form method="post">
    <label>Name: <input type="text" name="name" required></label><br><br>
    <label>Email: <input type="email" name="email" required></label><br><br>
    <label>Message:<br><textarea name="message" rows="4" required></textarea></label><br><br>
    <input type="submit" value="Send">
</form>
<?php
}
?>

🧠 Quiz - Forms & User Input in PHP

Top