Forms are the most important part of any dynamic website. They allow users to interact with your application by sending data to the server, which PHP then processes and stores.
An HTML form uses the <form> tag. To connect it to PHP, you need two essential attributes:
post or get).<!-- simple_form.html -->
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
When the user clicks the "Submit" button, the form data is sent to the file specified in the action attribute. PHP captures this data using its superglobal variables.
<?php
// welcome.php
echo "Welcome " . $_POST["name"] . "<br>";
echo "Your email address is: " . $_POST["email"];
?>
name attribute, NOT their id. Always ensure your inputs have unique names.
How you send data matters for both security and functionality.
| Method | Description |
|---|---|
| POST | Data is hidden in the HTTP body. Best for sensitive info (passwords) and large data. |
| GET | Data is visible in the URL. Best for non-sensitive info (search queries) and bookmarking. |
htmlspecialchars() when echoing user input to prevent Cross-Site Scripting (XSS) attacks.
action attribute points to the processing PHP file.method="post" for submitting passwords or large text.name attribute in HTML becomes the key in PHP's $_POST or $_GET arrays.