☰ See All Chapters |
PHP Form Handling
HTML from is used to submit the data from browser to servers. A form is a section of an HTML page that can contain a variety of controls. The form request may be get or post. A form tag has two main attributes:
action: Specifies where to send the form-data when the form is submitted. Possible values:
An absolute URL - points to another web site (like action="https://www.java4coing.com/example.htm")
A relative URL - points to a file within a web site (like action="login.php")
method: it defines the type of request. Specifies the HTTP method to use when sending form-data. Default value is get. The form method may be get or post.
Methods to retrieve the values from HTML form
To retrieve data from get request, we use $_GET array, for post request $_POST array. Form tag is used to communicate with PHP.
PHP Get Form
When a request is sent using GET method, data will be attached to the URL as a query string. Size of URL is limited, because of this we can send limited amount of data using GET method. GET method is not secure because of attaching the data in the URL which can be seen by the user. GET is used for bookmarking. We use $_GET array to retrieve data from form.
PHP Get Form example
login.html
<form action="login.php" method="get"> Name: <input type="text" name="name" /> <input type="submit" value="Submit" /> </form> |
login.php
<?php $name=$_GET["name"];//receiving name field value in $name variable echo "Welcome, $name"; ?> |
Project directory structure
Output
PHP Post Form
When a request is sent using POST method, data will be sent to the server along with the Http Request body. Using POST we can send unlimited amount of data because the body can take any number of characters, size is not fixed. POST method is secure because it carries the data in the request body and does not exposes the data in the URL. POST is used for carrying secure data and cannot be used for bookmarking. We use $_POST array to retrieve data from form.
PHP Post Form example
login.html
<form action="login.php" method="post"> <table> <tr> <td>Name:</td> <td><input type="text" name="name" /></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Login" /></td> </tr> </table> </form> |
login.php
<?php $name = $_POST["name"]; $password = $_POST["password"];
echo "Welcome: $name, your password is: $password"; ?> |
Project directory structure
Output
All Chapters