w1coding.comAll tutorials

PHP Forms

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

PHP Form Handling

Forms allow users to input data on a website. PHP can be used to handle form submissions, validate data, and display results.

Creating a Simple Form

To create a form in HTML, use the <form> tag:

      
        <form action="process.php" method="post">
          Name: <input type="text" name="name">
Email: <input type="email" name="email">
</form>

Processing Form Data in PHP

When the form is submitted, PHP can access the data using the $_POST superglobal:

      
        <?php
          if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $name = $_POST['name'];
            $email = $_POST['email'];

            echo "Hello, $name! Your email is $email.";
          }
        ?>
      
    

Form Validation

To validate form data, you can check if the inputs are empty:

      
        <?php
          if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if (empty($_POST['name']) || empty($_POST['email'])) {
              echo "Name and email are required.";
            } else {
              echo "Form submitted successfully.";
            }
          }
        ?>
      
    

Activity

Try It Yourself!

Create a form that collects the user's name, email, and message. Display the submitted data on a new page.

Quiz