PHP Login Form

From CoderLearner
Jump to: navigation, search

PHP Login Form

User requires to enter password and user name. A correct user name and password, user will direct to the home page,and an incorrect user name and password, user will direct to the login page.

Step 1(login.php)

  • Check whether the login name and password is not empty.
if (!empty($_POST['login_name']) && !empty($_POST['login_password']))
  • When user tries to submit an empty login form, it displays the following message.
$msg = 'please enter your name and password correctly!<br/>';
  • When the user name and password are matched with the password and user name that are predefined. Then, we redirect user to the home.php page.
if (($_POST['login_name'] == $user) &&
           ($_POST['login_password'] == $pass)) {
      header('location: home.php?name=' . $_POST['login_name']);
   }
  • When the user name and password are not matched with what have already predefined, it redirects user to the login page.
header('location:login.php');
  • A complete code.
<?php
$user = 'user100';
$pass = 'user100';
$msg = "";
if (!empty($_POST['login_name']) && !empty($_POST['login_password'])) {

   if (($_POST['login_name'] == $user) &&
           ($_POST['login_password'] == $pass)) {
      header('location: home.php?name=' . $_POST['login_name']);
   } else {
      header('location:login.php');
   }
} else {
   $msg = 'please enter your name and password correctly!<br/>';
}
?>

<html>
   <head>
      <title>Login Form</title>
   </head>
   <body>
      <b><?php echo $msg; ?></b>
      <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
         <table border="0">
            <tr>
               <td>
                  Login Name:
               </td>
               <td>
                  <input type="text" name="login_name" size="20" maxlength="20"/>
               </td>
            </tr>
            <tr>
               <td>
                  Password:
               </td>
               <td>
                 <input type="password" name="login_password" size="20" maxlength="20" />
               </td>
            </tr>
            <tr>
               <td colspan="2"><input type="submit" value="submit" /></td>
            </tr>
         </table>
      </form>
   </body>
</html>

Step 2(home.php)


<?php

if ($_GET['name']) {
	echo 'Welcome !!! <br/>';
	echo 'your name is ' . $_GET['name'] . '<br/>';
}
?>

Try It

  • user: user100 and password:user100