PHP Form Handling


Form handling is the process of:

  • Displaying an HTML form
  • Collecting user input
  • Sending data to a PHP script
  • Processing or storing that data
php-form-handling

HTML Form Example

<!DOCTYPE html>
<html>
<head>
    <title>Simple Form</title>
</head>
<body>
    <form action="process.php" method="POST">
        Name: <input type="text" name="username"><br><br>
        Email: <input type="email" name="email"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html> 

Explanation:

  • action="process.php": sends form data to process.php file
  • method="POST": The method="POST" attribute sends user data securely through the HTTP request body.

PHP Script to Handle Form Data (process.php)

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

    echo "Name: $name<br>";
    echo "Email: $email";
}
?> 

Form Handling Methods: GET vs POST

Method Description Use For
GET Appends data to the URL Search, bookmarking
POST Sends data invisibly in HTTP body Login, registration

Superglobals for Form Handling

Variable Use
$_POST Handles form data via POST
$_GET Handles form data via GET
$_REQUEST Handles both GET and POST
$_SERVER Info about request/method

notepad
  • Construct an HTML form by adding input fields and specifying both action and method attributes.
  • Use either the POST or GET method to transfer data to a PHP script.
  • Process the incoming data by accessing it through the $_POST or $_GET superglobals.
  • Make sure to sanitize and validate input data before you display or store it.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.