Lokang 

PHP and MySQL

Form

Creating a form in PHP involves both HTML for the form structure and PHP to process the form data. Below is an example of a simple form that collects a user's name and email, then processes and displays the input.

HTML Form

Create a file called form.html:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Simple Form</title>
</head>
<body>
   <form action="process.php" method="post">
       <label for="name">Name:</label>
       <input type="text" id="name" name="name" required><br><br>
       
       <label for="email">Email:</label>
       <input type="email" id="email" name="email" required><br><br>
       
       <input type="submit" value="Submit">
   </form>
</body>
</html>

PHP Processing Script

Create a file called process.php:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
   // Collect the form data
   $name = htmlspecialchars($_POST['name']);
   $email = htmlspecialchars($_POST['email']);
   // Display the collected data
   echo "<h1>Form Submission</h1>";
   echo "<p>Name: " . $name . "</p>";
   echo "<p>Email: " . $email . "</p>";
}
?>

Explanation

HTML Form (form.html):

  • The form has two input fields: one for the user's name and one for their email.
  • The action attribute of the form specifies that the form data will be sent to process.php.
  • The method attribute is set to post, meaning the form data will be sent via the HTTP POST method.

PHP Processing Script (process.php):

  • The script first checks if the form was submitted using the POST method.
  • It then collects the form data using $_POST and sanitizes it with htmlspecialchars() to prevent XSS (Cross-Site Scripting) attacks.
  • Finally, it displays the submitted data on the web page.

Make sure both files are saved in the same directory on your server. When you open form.html in your browser and submit the form, process.php will display the submitted data.