Databases Reference
In-Depth Information
// If no username or password has been entered,
// show the login page
if(empty($username) ||
empty($password) )
{
// Generate HTML form
}
else
{
// Process form data
}
?>
In script files that both generate the form and process the submitted data, the form
action is set to the name of the script file itself. As our login form is the start page of
our application, we'll call the script
index.php
so that it's the index file. We described
index files in “Web Server Index Files” in Chapter 13. The form action in the
in
dex.php
script is then also
index.php
:
<form action="index.php" method="POST">
Instead of typing the name of the script into the form action field, we can simply access
the
PHP_SELF
entry from the
$_SERVER
superglobal array that we first saw in “The PHP
Predefined Superglobal Variables” in Chapter 14:
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="POST">
When the PHP script is processed, the form action is set to the address of the script
before the HTML is sent to the browser.
Passing a Message to a Script
If the user submits the form without providing any authentication details, or submits
details that are incorrect, we should display the form again with an appropriate error
message. We can modify our
index.php
script to display the login form if a message has
been passed to it for display, in addition to the previous check for an empty username
or password:
// If no username or password has been entered, or there's a message
// to display, show the login page
if(empty($username) || empty($password) || isset($message) )
{
// Display the message (if any), and the login form
}
else
{
// Try to authenticate the user against the database
...
// If unsuccessful, pass an error message and call the form again.
}
?>