June 6, 2019
PHP MySQL User Login Code
User Login code with PHP and MySQL is very simple. To complete process of Login and Logout there are 4 pages.
config.php : Define all database connection and configuration in this page.
login.php : Containing Login Form and PHP login code.
account.php : In this page display Welcome Message and Logout button.
logout.php : It will contain only PHP code for user logout.
config.php
<?php ob_start(); session_start(); //GLobal variable........................... global $DB; //DataBase Connection Start................. $DB["dbName"] ='database_name'; $DB["host"] = 'localhost'; $DB["user"] = 'root'; $DB["pass"] = ''; $conn = mysqli_connect($DB["host"], $DB["user"], $DB["pass"], $DB["dbName"]); ?>
login.php
<?php ob_start(); include "config.php"; // LOGIN QUERY********************** if($_REQUEST['loginsubmit'] == 'Log In'){ $sql = "SELECT * from wt_member WHERE email = '".$_REQUEST['loginemail']."' AND password = '".$_REQUEST['loginpassword']."'"; $query = mysqli_query($conn, $sql); $num = mysqli_num_rows($query); if($num > 0){ $res = mysqli_fetch_array($query); $_SESSION['UID'] = $res['id']; $_SESSION['NAME'] = $res['name']; header("location:account.php"); } else { $_SESSION['sess_mess'] = 'Your email or password is invalid!!!'; header("location: $_SERVER[HTTP_REFERER]"); } } ?> <html> <head> <title>Login Page</title> </head> <body> <h1>User Login Form</h1> <?php if(!empty($_SESSION['sess_mess'])){ ?> <p><?php echo $_SESSION['sess_mess'];?></p> <?php } ?> <form action="" method="post" id="loginfrm" name="loginfrm"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td>Email ID : </td> <td><input type="text" name="loginemail" id="loginemail" placeholder="Email-Id" required="required" /></td> </tr> <tr> <td>Password : </td> <td><input type="password" name="loginpassword" id="loginpassword" placeholder="Password" required="required" /></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" value="Log In" name="loginsubmit" id="loginsubmit" /></td> </tr> </table> </form> </body> </html>
account.php
<html> <head> <title>User Account Page</title> </head> <body> <h1>Welcome to Account Page</h1> <a href="logout.php">Logout</a> </body> </html>
logout.php
<?php ob_start(); session_start(); session_destroy(); // Redirect to login page with message $_SESSION['sess_mess'] = 'You are logged out.'; header("location:login.php"); ?>