In this tutorial, we aim to learn how to process HTML forms using PHP. We'll explore how to collect data from forms using both POST and GET methods and how to handle this data in PHP.
By the end of this tutorial, you will be able to:
Prerequisites: Basic understanding of HTML and PHP.
HTML forms are a way to collect user input. The <form>
element is used to create an HTML form.
HTML Form example:
<form action="" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
When a user fills out a form and clicks the submit button, the form data is sent for processing to a PHP file specified in the action
attribute of the <form>
tag.
The form data can be sent as HTTP POST or GET methods. These are superglobals, which means that they are always accessible, regardless of the scope, and you can access them from any function, class, or file without having to do anything special.
URL?name=value&name=value
Here's a simple form where users can enter their name and email. We've set the method to POST because we don't want sensitive data like email addresses visible in the URL.
HTML Form (form.html
):
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
PHP Form Processing (welcome.php
):
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
In the PHP script, the $_POST
superglobal array is used to collect the form data.
HTML Form (form.html
):
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
PHP Form Processing (welcome_get.php
):
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
In this example, we use the $_GET
superglobal array. The information sent from the form with the GET method is visible to everyone and displayed in the URL.
In this tutorial, we've learned how to process HTML forms using PHP. We covered the basics of HTML forms, the difference between the GET and POST methods, and how to use PHP to handle the form data.
Remember, the best way to learn is by doing. Practice by building as many forms as you can and processing them using PHP. Happy learning!