PHP Forms


The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.

Example!
PHP Code
  1. <html>
  2. <body><form action="index.php" method="post">
  3. First Name: <input type="text" name="name" />
  4. Real Age: <input type="text" name="age" />
  5. <input type="submit" />
  6. </form></body>
  7. </html>


The example HTML page above contains two user input fields and a submit button.
Here’s what the code does:

  • action: Specifies the PHP file (index.php) that will process the form data.
  • method="post": Ensures the data is sent securely (hidden from the URL).
  • name: Each <input> field is assigned a name attribute (e.g., name and age), which will be used to reference the data in PHP.



The "index.php" file looks like this:
index.php
  1. <html>
  2. <body>Hello <?php echo htmlspecialchars($_POST["name"]); ?>.
  3. You are <?php echo htmlspecialchars($_POST["age"]); ?> years old. Welcome to our website.</body>
  4. </html>


A sample output of the above script may be:

Welcome Joshua.
You are 25 years old. Welcome to our website



Here’s what’s happening:

  • $_POST["name"]: Retrieves the value of the name field.
  • $_POST["age"]: Retrieves the value of the age field.
  • htmlspecialchars(): Ensures that any HTML or special characters entered into the form are safely displayed, preventing XSS (Cross-Site Scripting) attacks.



Security Note


Always validate and sanitise user input when dealing with forms to prevent security vulnerabilities like XSS and SQL injection.

  • Use htmlspecialchars() to safely display user input.
  • Filter inputs with PHP's filter_input() and filter_var() functions.
  • For advanced scenarios, use prepared statements with databases to handle form submissions securely.
Joshua's Avatar
Author:
Views:
2,584
Rating:
There are currently no comments for this tutorial, login or register to leave one.