HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Form Handling

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.


1. Basic Form Structure

An HTML form uses the <form> tag. To connect it to PHP, you need two essential attributes:

  • action: The filename of the PHP script that will process the data.
  • method: How the data is sent (usually 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>

2. Receiving Data in PHP

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"];
?>
The "name" Attribute: PHP identifies form fields using their name attribute, NOT their id. Always ensure your inputs have unique names.

3. Choose Your Method

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.
Security Alert: Never process form data directly without validation and sanitization. Users can send malicious code through input fields (XSS/SQL Injection).
Pro Tip: Use htmlspecialchars() when echoing user input to prevent Cross-Site Scripting (XSS) attacks.

Key Takeaways

  • The action attribute points to the processing PHP file.
  • Use method="post" for submitting passwords or large text.
  • The name attribute in HTML becomes the key in PHP's $_POST or $_GET arrays.
  • Always sanitize user input before displaying it back or saving to a database.