HTML forms are one of the most popular ways of collecting information from the user.
They consist of a series of fields-called input in the HTML world and a final submit button.
In HTML, the form tag contains two attributes.
Attribute | meaning |
---|---|
action | where the form will be submitted |
method | specifies the HTTP method that the form will use (GET or POST). |
Here is the login.html and go to http://localhost:8000/login.html.
<!DOCTYPE html> <html lang="en"> <body> <p>Enter your details to login:</p> <form action="authenticate.php" method="post"> <label>Username</label> <input type="text" name="username" /> <label>Password</label> <input type="password" name="password" /> <input type="submit" value="Login"/> </form> </body> </html>
The form defined in the preceding code contains two fields, one for the username and one for the password.
You can see that they are identified by the attribute name.
If you try to submit this form, the browser will show you a Page Not Found message, as it is trying to access http://localhost:8000/authenticate.php and the web server cannot find it.
authenticate.php is as follows:
<?php $submitted = !empty($_POST); ?> <!DOCTYPE html> <html> <body> <p>Form submitted? <?php echo (int) $submitted; ?></p> <p>Your login info is</p> <ul> <li><b>username</b>: <?php echo $_POST['username']; ?></li> <li><b>password</b>: <?php echo $_POST['password']; ?></li> </ul> </body> </html>
$_POST is an array that contains the parameters received by POST.
Here, we first ask if that array is not empty-note the ! operator.
Afterwards, we just display the information received, just as in index.php.
The keys of the $_POST array are the values for the argument name of each input field.