๐Ÿ“ Web Development

PHP Forms: GET, POST and Handling User Input

Aug 22, 20265 min read7 viewsBy Flow

PHP forms are how a visitor talks back to your site. A login box, a search bar, a contact page โ€” all of them are a form sending data to PHP. This lesson covers reading that data, checking it, and the one habit that keeps it safe.

A form and the PHP that reads it

The HTML gathers the data. The action says where to send it, and method says how.

<form action="welcome.php" method="post">
    Name: <input type="text" name="username">
    <button type="submit">Send</button>
</form>

Now welcome.php picks it up.

<?php
$name = $_POST["username"];

echo "Hello, " . $name;
?>

Output:

PHP forms output after a POST submit, printing Hello, Ayesha from the username field

The link between the two is the name attribute. name="username" in the HTML becomes $_POST["username"] in PHP. Change one and the other stops working โ€” this is the single most common reason a form "does nothing".

GET or POST?

Both send data. The difference is where it travels.

<?php
// search.php?query=arrays&page=2

echo $_GET["query"];
echo "<br>";
echo $_GET["page"];
?>

Output:

PHP forms using GET: the query and page values read from the URL and printed on the page

GET puts the values in the URL, so they are visible, bookmarkable and shareable. That makes it right for searches and filters.

POST sends them in the request body, out of the URL. Use it for anything private or anything that changes data โ€” logins, contact forms, deleting a record.

A simple rule: if refreshing the page twice should not do the thing twice, use POST.

Check the field exists before you use it

Open welcome.php directly, without submitting the form, and $_POST["username"] does not exist. PHP warns and you get nothing.

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (isset($_POST["username"]) && trim($_POST["username"]) !== "") {
        echo "Hello, " . trim($_POST["username"]);
    } else {
        echo "Please enter your name.";
    }
} else {
    echo "Nothing submitted yet.";
}
?>

<form method="post">
    Name: <input type="text" name="username">
    <button type="submit">Send</button>
</form>

Output:

PHP forms required field check passing, printing Hello, Ayesha with the form still shown

Two checks, both worth the habit. REQUEST_METHOD asks whether the page was reached by a submit at all. isset() plus trim() catches the field being missing and the user typing only spaces.

Remember from PHP strings that trim() returns a new string โ€” it does not clean the original in place.

Never print user input as it arrives

This is the part that matters most, and it is one line.

Whatever the visitor types lands in your HTML. If they type HTML, the browser will treat it as HTML. htmlspecialchars() turns those characters into harmless text so they display instead of running.

<?php
$comment = $_POST["comment"] ?? "";

// Wrong โ€” prints whatever they typed straight into the page
echo $comment;

echo "<hr>";

// Right โ€” shows it as text, whatever it contains
echo htmlspecialchars($comment);
?>

<form method="post">
    Comment: <input type="text" name="comment">
    <button type="submit">Send</button>
</form>

Output:

PHP forms escaping comparison: unescaped input renders as bold, htmlspecialchars prints the tags as text

Type <b>hello</b> into the form and the difference is immediate: the first line goes bold, the second prints the tags. The first is the door that cross-site scripting walks through.

Make it a reflex: escape on the way out, every time you echo something a user gave you.

A small form that checks itself

Putting it together โ€” one file that shows the form and handles it.

<?php
$errors = [];
$name = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name  = trim($_POST["name"] ?? "");
    $email = trim($_POST["email"] ?? "");

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

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "That email does not look right.";
    }

    if (!$errors) {
        echo "Thanks, " . htmlspecialchars($name) . "!";
    }
}

foreach ($errors as $error) {
    echo htmlspecialchars($error) . "<br>";
}
?>

<form method="post">
    Name:  <input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>"><br>
    Email: <input type="text" name="email"><br>
    <button type="submit">Send</button>
</form>

Output:

PHP forms validation errors: name is required and the email does not look right

filter_var() with FILTER_VALIDATE_EMAIL checks the shape of an email address for you โ€” far more reliable than anything you would write by hand.

Errors collect in an array and get printed with a foreach, exactly the pattern from PHP arrays.

One more detail worth copying. The value="<?php echo htmlspecialchars($name); ?>" on the name field keeps what the visitor already typed when the page reloads with an error. Without it they lose the whole form on every mistake, which is the fastest way to make someone give up. Note it is escaped there too โ€” anything printed inside an attribute needs it just as much as anything printed on the page.

Three mistakes with PHP forms

The name attribute does not match. name="user" in the HTML but $_POST["username"] in PHP. The form submits fine and nothing arrives.

Reading $_POST without checking. Open the page directly and the key is not there. Guard with REQUEST_METHOD and isset(), or use ?? "".

Echoing input unescaped. htmlspecialchars() is one function call and it closes the most common hole beginners leave open.

Common questions about PHP forms

The questions that come up most often once a form starts talking to PHP.

What is the difference between GET and POST in PHP?

GET puts values in the URL, so they can be seen, bookmarked and shared โ€” right for searches and filters. POST sends them in the request body, so they stay out of the URL โ€” right for logins, contact forms and anything that changes data.

Why is my PHP form not receiving any data?

Almost always one of three things: the name attribute in the HTML does not match the key you read in PHP, the form method is GET while you read $_POST, or the submit button is outside the <form> tag.

How do I stop the undefined array key warning on $_POST?

Check before reading. Either wrap the code in if ($_SERVER["REQUEST_METHOD"] === "POST"), use isset($_POST["field"]), or supply a fallback with $_POST["field"] ?? "".

Do I really need htmlspecialchars on every output?

On anything a user supplied, yes. Without it, text a visitor types is treated as HTML by the browser, which is how cross-site scripting starts. It costs one function call and removes the whole class of problem.

Can I leave the form action attribute empty in PHP?

Yes. <form method="post"> with no action submits back to the same page, which is what you want when one file both shows the form and handles it. Writing action="" does the same thing.

How do I keep the values in a PHP form after submitting?

Echo the submitted value back into the input: value="<?php echo htmlspecialchars($name); ?>". This is called a sticky form, and it stops the visitor retyping everything when one field fails validation.

What is next

PHP forms tell you what the visitor just typed. But click through to the next page and your site has forgotten them completely โ€” the name they entered is gone, and so is the fact they logged in at all.

Fixing that is what sessions are for, and that is the next lesson: PHP sessions.

Need to go back? PHP strings covers trim(), and PHP if else covers the checks used above.

Comments

Loading comments...

Link copied to clipboard