PHP

PHP HTML Form


 

Let’s create a basic form that takes a user's name and email address and then processes and displays the input using PHP.
Creating two files, one for the HTML form in html format (‘form.html’) and second one for the PHP in php format
(‘formData.php’).
 

HTML FORM (index.html):

<h2>PHP Form</h2>
<form action="formData.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>

 

PHP Process (formData.php):

<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Collect form data
        $name = $_POST["name"];
        $email = $_POST["email"];

        // Display the form data
        echo "<p>Name: $name</p>";
        echo "<p>Email: $email</p>";
    }
?>

 

When the user fills the form and clicks the submit button, the form data is sent to the “formData.php” with the HTTP POST method.

 

The work flow:

  1. Creating a HTML form using ‘<form>’ tag with two input fields.
  2. The ‘action’ attribute in form used to submit the form data.
  3. The PHP file (‘formData.php’) checks if the request method is POST,
    Retrieves the form data using ‘$_POST’, and then displays the submitted data.

 

Note: HMTL form submitting can be achieved using GET method. $_GET and $_POST are php superglobals which are used to collect data from the Form.


GET vs. POST

Get and Post are the two methods that the browser client can send information to the server. These methods are commonly used with HTML forms.

 

1. GET Method:

  1. Data is sent as a query string in the URL.
  2. Data is visible in the URL, so it's not suitable for sensitive information.
  3. Limited amount of data can be sent (about 2048 characters).
  4. It is used for data retrieval, not for sensitive information.

 

2. POST Method:

  1. Data is sent in the body of the HTTP request.
  2. Data is not visible in the URL, making it suitable for sensitive information.
  3. Can be used to send larger amounts of data.
  4. Used for data submission, especially for forms handling sensitive information.