Codeskill

Learn to code, step by step

Form Handling in PHP: Collecting User Input

Form handling in PHP – how to collect user input from an HTML form and process it on the server.

Understanding PHP form handling

Form handling means reading data a user submits from a web page and using it in your PHP script.

The basics of a PHP form

A form setup has two parts: the HTML form (user input) and the PHP script (processing). The form’s action attribute says where to send the data. To handle it in the same file, use $_SERVER['PHP_SELF'] as the action value.

Creating a simple PHP form

Start with a form that asks for a name:

HTML form:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    Name: <input type="text" name="name">
    <input type="submit">
</form>

Processing form data in PHP

Submitted data arrives in $_GET[], $_POST[], or $_REQUEST[]. For most forms, use $_POST[] – it’s more secure than putting data in the URL via $_GET[].

PHP script to handle the form:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = htmlspecialchars($_REQUEST['name']);
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo "Hello, $name!";
    }
}
?>

We check $_SERVER["REQUEST_METHOD"] to confirm the form was submitted as POST before processing.

Validating form data

Never trust raw user input. Validate it matches what you expect, and sanitise it before use.

Basic validation rules

  • Required fields: check inputs are filled in.
  • Proper format: check the data shape (email addresses, phone numbers, etc.).
  • Sanitisation: clean input to reduce risks like SQL injection.

Example of form validation:

<?php
$nameErr = $emailErr = "";
$name = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
            $nameErr = "Only letters and white space allowed";
        }
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

Keeping form values after submission

If validation fails, repopulate the fields so the user does not have to retype everything. Put the PHP variables in each input’s value attribute:

Example:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Name: <input type="text" name="name" value="<?php echo $name;?>">
    <span class="error">* <?php echo $nameErr;?></span>
    <br><br>
    E-mail: <input type="text" name="email" value="<?php echo $email;?>">
    <span class="error">* <?php echo $emailErr;?></span>
    <br><br>
    <input type="submit" name="submit" value="Submit">
</form>

Working with select, checkbox, and radio button

select, checkbox, and radio inputs need slightly different handling – check whether the option was actually selected or checked.

Example with radio button:

<?php
if (isset($_POST['gender'])) {
    $gender = $_POST['gender'];
    echo "Gender: $gender";
}
?>

Forms are how users talk to your site. Get the POST handling, validation, and sanitisation right and the rest tends to follow.

PreviousUnderstanding PHP Operators: Logic in Action