PHP: Dealing with Forms

One of the most powerful features of PHP is the way it handles HTML forms.
The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts.

A simple HTML form

<form action="action.php" method="post">
 <p>Your name: <input type="text" name="name" /></p>
 <p>Your age: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old
  • When the user fills in this form and hits the submit button, the action.php page is called.
  • htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page.
  • For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters.
  • The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP.

Related concepts

PHP: Dealing with Forms — Structure map

Clickable & Draggable!

PHP: Dealing with Forms — Related pages: