This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
isset function not working correctly
(1 answer)
Closed 5 years ago.
I am trying to login with a username or email and password in php. As i try to login it says password do not match, as i have typed the correct username and password. I guess something going wrong with my hashing password or session variable. Can anybody help me with my code?
Here is my login.inc.php file
<?php
session_start();
if (isset($_POST['Loginsubmit'])) {
include 'dbh.inc.php';
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password= mysqli_real_escape_string($conn, $_POST['password']);
// Error handlers
if (empty($username) || empty($password)) {
header("Location: ../index.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM users WHERE username= '$username' OR email= '$username'";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: ../index.php?login=error");
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
// De-hashing the password
$hashedPasswordCheck = password_verify($password, $row['password']);
if ($hashedPasswordCheck == false) {
header("Location: ../index.php?login=error");
exit();
} elseif ($hashedPasswordCheck == true) {
// Log in the user here
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['surname'] = $row['surname'];
$_SESSION['email'] = $row['email'];
$_SESSION['username'] = $row['username'];
$_SESSION['bdate'] = $row['bdate'];
$_SESSION['gender'] = $row['gender'];
header("Location: ../home.php");
exit();
}
}
}
}
} else {
header("Location: ../index.php?login=error");
exit();
}
And here is my part of index.php file where i am taking the inputs
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mysite</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
<link href="css/bootstrapValidator.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/bootstrapValidator.min.js" type="text/javascript"></script>
<script src="https://use.fontawesome.com/465fa6787a.js"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top" id="navbar">
<div class="container">
<!-- logo -->
<div class="navbar-header">
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#myNav">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
BRAND
</div>
<!-- menu items -->
<div class="collapse navbar-collapse" id="myNav">
<div class="nav navbar-nav pull-right">
<form class="navbar-form navbar-right" action="includes/login.inc.php" method="post">
<div class="input-group">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user"></span>
</span>
<input type="text" class="form-control" placeholder="Username">
</div>
<div class="input-group ">
<span class="input-group-addon">
<span class="glyphicon glyphicon-lock"></span>
</span>
<input type="password" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-success" name="Loginsubmit">Login</button>
</form>
</div>
</div>
</div>
</nav>
Related
I have a login form(index.php) which allows students to access their portal, the students' registration number and password is then checked if inserted(login.php) and proceeds to a class(StudentLogin.php) which will then allow the students access their portal if at all the credentials match with the ones in the database. On entering the correct credentials, the process doesn't proceed to the stud_page.php.....I would appreciate any help on this cause i don't understand what is happening.
Below is the index.php:
<?php
//Start session
if(!isset($_SESSION)) { session_start(); }
unset($_SESSION['ID']);
unset($_SESSION['REG_NUM']);
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portal System</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="static/css/bootstrap.min.css">
<link rel="stylesheet" href="static/css/style.css">
<!-- <link rel="stylesheet" href="static/css/style.css"/> -->
</head>
<body>
<!-- Header -->
<nav class="navbar navbar-fixed-top" style="background-color: green;" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">portal</a>
</div>
</div><!-- /.container-fluid -->
</nav>
<!-- End Header -->
<div class="background">
<div class="container">
<div class="jumbotron bg-success text-warning">
<h1 class="text-center">portal</h1>
<h3 class="text-center"> Welcome to The Portal.</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4">
<div class="login-con">
<h3>Student Log-in</h3><hr>
<?php
if(isset($_SESSION['ERROR_MSG_ARRAY']) && is_array($_SESSION['ERROR_MSG_ARRAY']) && COUNT($_SESSION['ERROR_MSG_ARRAY']) > 0) {
foreach($_SESSION['ERROR_MSG_ARRAY'] as $msg) {
echo "<div class='alert alert-danger'>";
echo $msg;
echo "</div>";
}
unset($_SESSION['ERROR_MSG_ARRAY']);
}
?>
<form action="process/login.php" method="POST" role="form">
<div class="form-group has-warning has-feedback">
<label for="reg_num">Registration Number</label>
<input type="text" name="reg_num" id="reg_num" class="form-control" autocomplete="off" placeholder="Registration Number">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-warning has-feedback">
<label>Password</label>
<input id="password" type="password" autocomplete="off" class="form-control" placeholder="Password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<button type="submit" onclick="showSomeMessage()" name="submit" class="btn btn-info">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
login.php below:
<?php
require("../admin/database.php");
require("../class/StudentLogin.php");
if(isset($_POST['submit'])){
$regnum = trim($_POST['regnumber']);
$password = trim($_POST['password']);
$loginStud = new StudentLogin($reg_num, $password);
$rtnlogin = $loginStud->Studlogin();
}
$conn->close();
?>
Then the StudentLogin class is:
<?php
class StudentLogin
{
private $_regnumber;
private $_password;
public function __construct($c_reg_num, $c_password){
$this->_regnumber = $c_reg_num;
$this->_password = $c_password;
}
public function StudLogin(){
global $conn;
// starting session
session_start();
// valiidate errors
$error_msg_array = array();
// error msg
$error_msg = FALSE;
if($this->_reg_num == ""){
$error_msg_array[] = "Please input your Registration Number";
$error_msg = TRUE;
}
if($this->_password == ""){
$error_msg_array[] = "Please input your password";
$error_msg = TRUE;
}
if($error_msg){
$_SESSION['ERROR_MSG_ARR'] = $error_msg_array;
header("location: http://localhost/project/index.php");
exit();
}
$sql = "SELECT * FROM students WHERE regnumber ='$reg_num' AND password ='$password' LIMIT 1";
if(!$stmt = $conn->prepare($sql)){
echo $stmt->error;
} else {
$stmt->bind_param("ss", $this->_reg_num, $this->_password);
$stmt->execute();
$result = $stmt->get_result();
}
if($result->num_rows > 0) {
// login successful
$row = $result->fetch_assoc();
// session creation
session_regenerate_id();
$_SESSION['reg_num'] = $row["regnunmber"];
$_SESSION['name'] = $row["name"];
session_write_close();
header("location: http://localhost/project/stud_page.php");
} else {
// Login failed
$error_msg_array[] = "The Registration Number and Password you entered is incorrect.";
$error_msg = TRUE;
if($error_msg) {
$_SESSION['ERROR_MSG_ARR'] = $error_msg_array;
header("location: http://localhost/project/index.php");
exit();
}
$stmt->free_result();
}
$result->free();
return $result;
}
}
?>
MySQL database, table students contains the following columns:
$sql="INSERT INTO `students`(`name`, `education`, `regnumber`, `nationality`, `gender`, `phone`, `photo`, `branch`,`password`)
VALUES ('$name','$education','$reg_num','$nationality','$gender','$phone','$target_file','$branch','$ency_pass')";
You have validation on login.php, which is not loaded before form is send.
And if you can i would recommend you using dibi, because this work with database is not properly right and can cause some problems if u are going to use that in production
https://dibiphp.com/en/
I have this example code for logging in two users namely 'user' and 'admin'. How do you validate each two when logging in so that after successful logged in it will redirect them to their respective pages.
HTML Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="stylelogin.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Welcome</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-step-backward"></span>Back</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="loginmodal-container">
<h1>Login to Your Account</h1><br>
<form action="Model/loginbackend.php" method="post">
<input type="text" name="username" placeholder="Username" autofocus required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" name="login" class="login loginmodal-submit" value="Login">
</form>
<div class="login-help">
No account? Register Here
</div>
</div>
</div>
</div>
</div>
</body>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
I have this sample php code.
PHP Code
<?php
include "connection.php";
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
$sql = "select * from users where username = '$username' and password = '$password'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if($row){
$_SESSION["user_id"] = $row["userid"];
header('Location: /laurence/FirstDayTraining/Model/users.php');
}
else
{
$sql = "select * from admin where adminusername = '$username' and adminpassword = '$password'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION["adminuser_id"] = $row["adminid"];
header('Location: /laurence/FirstDayTraining/Model/admin.php');
}
mysqli_close($conn);
}
?>
In this condition
if($row){
$_SESSION["user_id"] = $row["userid"];
header('Location: /laurence/FirstDayTraining/Model/users.php');
}
else
{
$sql = "select * from admin where adminusername = '$username' and adminpassword = '$password'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION["adminuser_id"] = $row["adminid"];
header('Location: /laurence/FirstDayTraining/Model/admin.php');
}
this will redirect to their respective pages. But when I put any input any my textbox username and password. Example I will input random text like : for username asdu : for password asoda. The inputs that I used was not mainly found in my database. But it still redirects me to the admin page. Is there any correct way to validate my form.. Please help, I'm quite new to php. Thanks in advance.
You need to find out of mysqli has a result for you. You Can check it like this:
if ($result->num_rows) {
$row = mysqli_fetch_assoc($result);
$_SESSION["adminuser_id"] = $row["adminid"];
header('Location: /laurence/FirstDayTraining/Model/admin.php');
}
//this will check if something is returned by your query if not then dont redirect
You can add a role column in your database and assign each admins/ editors manually through script otherwise they will be a user by default. After that you can identify them easily
if( $row['role'] == 'admin')
$_SESSION['user_role'] = $row['role'] ;
in this i wannna get the username who is logged in and display it in the home page when the username is correct and registered in database .should i use session and where to use it.how it is been done
<?php
error_log("chk.php executing");
// Get values from form
include 'config.php';
foreach ($_POST as $key => $value) {
error_log($key);
}
//error_log($_POST['username']);
$username=$_POST['username'];
$password=$_POST['password'];
// Insert data into mysql
$qry = mysql_query("SELECT * FROM useraccount WHERE username='$username'");
if(!$qry) {
die("Query Failed: ". mysql_error());
} else {
$row=mysql_fetch_array($qry);
if ($username==$row['username']) {
if($username=='' || $password=='') {
error_log("some fields are empty");
//header("Location:login.php?id=Some fields are empty");
// header("Content-Type: text/html");
// {echo "<b>Some fields are empty</b>";}
} else if($username==$row['username'] && $password==$row['password']) {
error_log("logged in");
header('Location: home.html');
// header("Content-Type: text/html");
// {echo "<b>User name password verified</b>";}
//header("Location: home.html?id=$username");
} else {
error_log("password is incorrect");
// header("Content-Type: text/html");
// {echo "<b>username already taken or your password is incorrect. Please try again</b>";}
//header("Location:.php?id=username already taken or your password is incorrect. Please try again");
}}
else
error_log("username incorrect");
}
mysql_close();
?>
html,body
{
margin:0px;
height:100%;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
width: 60%;
margin: auto;
}
.content
{
width:100%;
height:400px;
}
.signup
{
height:500px;
}
.footer
{
position:relative;
background-color:black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>ASK</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="boot.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6">
<h1>school name</h1>
</div>
<div class="col-md-6">
<img src="../project/photo/l.png" height="150px"/>
</div>
</div>
</div>
</div>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#mynavbar">schoolName</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li><a href="about.html" target=_self>About Us</a></li>
<li><a href="infra.html" target=_self>Infrastructure</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="">Administration<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>staff login</li>
<li>staff details</li>
<li>class handling</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<form class="form-horizontal" action="chk.php" method="POST">
<div class="form-group">
<div class="col-xs-3">
<label for="username">Username:</label>
<input name="username" type="username" class="form-control" id="username" placeholder="Enter username">
</div></div>
<div class="form-group">
<div class="col-xs-3">
<label for="pwd">Password:</label>
<input name="password" type="password" class="form-control" id="password" placeholder="Enter password">
</div></div>
<!-- <div class="checkbox">
<label><input type="checkbox"> Remember me</label><br>
</div> -->
<button type="submit" class="btn btn-default">Submit</button><br>
</form>
</div>
<div class="footer navbar-fixed-bottom">
<p> Copyrights# ©WWW.schools.com</p>
</div>
</body>
</html>
first of all when username store in session on login time
<?php
session_start();
- List item
error_log("chk.php executing"); // Get values from form include 'config.php';
foreach ($_POST as $key => $value) { error_log($key); } //error_log($_POST['username']); $username=$_POST['username']; $password=$_POST['password']; // Insert data into mysql $qry = mysql_query("SELECT * FROM useraccount WHERE username='$username'"); if(!$qry) { die("Query Failed: ". mysql_error()); } else {
$row=mysql_fetch_array($qry);
if ($username==$row['username']) {
if($username=='' || $password=='') {
error_log("some fields are empty");
//header("Location:login.php?id=Some fields are empty");
// header("Content-Type: text/html"); // {echo "<b>Some fields are empty</b>";}
} else if($username==$row['username'] && $password==$row['password']) {
error_log("logged in");
$_SESSION['username']=$row['username'];
header('Location: home.html');
// header("Content-Type: text/html"); // {echo "<b>User name password verified</b>";}
//header("Location: home.html?id=$username");
} else {
error_log("password is incorrect");
// header("Content-Type: text/html"); // {echo "<b>username already taken or your password is incorrect. Please try again</b>";}
//header("Location:.php?id=username already taken or your password is incorrect. Please try again");
}}
else
error_log("username incorrect"); } mysql_close(); ?>
Another page we get this username and we change file name home.html to home.php
home.php
echo $_SESSION['username'];
?>
output username print this page
You can use SESSION . You have to use session_start() in every files that you want to display the username
else if($username==$row['username'] && $password==$row['password']) {
$_SESSION['username'] = $username; // store username name in session
error_log("logged in");
header('Location: home.html');
// header("Content-Type: text/html");
// {echo "<b>User name password verified</b>";}
header("Location: home.php?id=$username"); // redirect to home.php page
You can simply display the username by echo $_SESSION['username']; Don't forget to add session_start(); in your home.php. For more info please refer to this link http://php.net/manual/en/function.session-start.php
You should use session_start();
After successfully login,you can post username or email like this-
<?php
include_once'dbconnect.php';
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
//print logged in user's email as saved in database
echo $userRow['email'];
////print logged in user's username as saved in database
echo $userRow['username'];
?>
This is as per my database where-
'dbconnect.php'is connection file.
'users' is tablename.
You can use session_start(); and store the username into it.
//Initialize the session:
session_start();
<!doctype html>
<head>
.
.
.
</head>
<body>
.
.
<?php
$q = "SELECT * FROM useraccount WHERE username='$username'";
$r = $mysqli->query($q);
if ($r->num_rows == 1) {
$_SESSION = $r-> fetch_array(MYSQLI_ASSOC);
}
?>
.
</body>
</html>
You can take a look at my site for that same query at hiteachers.com
The codes for site is given below. Login cannot be authenticated with what I've done. Firstly, it will redirect to the login page as expected if not logged in. Then, after I clearly give the login details correctly, it won't redirect me to the site I want. Instead, it will remain on login page. Please help me...
<!--This is the page that I want to redirect after successful login-->
<?php
session_start();
if($_SESSION['loggedIn'])
{
header('Location: restaurant.php');
}
else
{
header('Location: login.php');
}
?>
<html lang="en">
<head>
<title>Welcome to Foodline</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="bootstrap/dist/css/bootstrap.min.css">
<link href="css/simple-sidebar.css" rel="stylesheet">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<style>
/* Remove the jumbotron's default bottom margin */
.jumbotron {
margin-bottom: 0;
}
/* Add a gray background color and some padding to the footer */
footer {
background-color: #f2f2f2;
padding: 25px;
}
</style>
</head>
<body>
<div class="jumbotron">
<div class="container text-center">
<h1><font face="Analecta">FOODLINE</font></h1>
<p>We provide the best service for our costumers</p>
</div>
</div>
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand"><font face="Analecta" color="white">>Restaurants<</font></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li>
Hamro Didi (HD)
</li>
<li>
HK
</li>
<li>
Junu Hotel
</li>
<li>
Junction Cafe
</li>
<li>
Laxmi Hotel
</li>
</ul>
</div>
</div>
</nav>
<footer class="container-fluid text-center">
<p>Foodline Official Website ©</p>
<p align="center">Logged in as: <div id="username" align="center"> <span class="glyphicon glyphicon-log-in"></span><?php
if(isset($_GET['id'])){
echo ' '.$_GET['id'];
}
else {
echo '(write) a 404 page';
}
?>
</div>
</p>
</footer>
</div>
<!--This is login.php-->
<?php
//session_start();
include("connection.php");
$msg='';
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from form
$username = $_POST['username'];
$password = $_POST['password'];
// To protect MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
//Input Validations
if($username == '') {
$_SESSION["login_user"] = $username; $msg = "Username missing";
header("location: login.php?msg=$msg");
}
if($password == '') {
$msg = "Password missing";
header("location: login.php?msg=$msg");
}
//Create query
$qry="SELECT * FROM user WHERE user_name='$username' AND user_password='$password'";
$result =mysql_query($qry)or die(mysql_error());
$output=mysql_fetch_assoc($result);
//Check whether the query was successful or not
if(!empty($output)) {
//Login Successful
$_SESSION['name']= $username;
$_SESSION['loggedIn'] = true;
header("location:restaurant.php?id=$username");
}
else {
//Login failed
$msg= "user name and password not found";
header("location:login.php?msg=$msg");
}
}
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="bootstrap/dist/css/bootstrap.min.css">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<style>
.jumbotron {
margin-bottom: 0;
}
</style>
</head>
<body>
<div class="jumbotron">
<div class="container text-center">
<h1><font face="Analecta">FOODLINE</font></h1>
<p>We provide the best service for our costumers</p>
</div>
</div>
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.php">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>Restaurants</li>
<li>Contact</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<h2><font face="Analecta">>Login from here<</font></h2>
<form role="form" name="login" action="login.php" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" name="username" placeholder="Enter username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" placeholder="Enter password" required>
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" value="login">Submit</button>
<br>
<br>
<?php
$msg = (isset($_GET['msg']) ? $_GET['msg'] : null); //GET the message
if($msg!='') echo '<p>'.$msg.'</p>'; //If message is set echo it
?>
</form>
<p>Not a user yet? Sign up here</p>
</div>
<footer class="container-fluid text-center">
<p>Foodline Official Website ©</p>
<p>Get deals:
<span class="glyphicon glyphicon-menu-right"></span>SignUp
</p>
</footer>
</body>
</html>
Uncomment:
//session_start();
From line 5 in login.php and change to this:
if(! $_SESSION['loggedIn']) {
header('Location: login.php');
}
in restaurant.php.
I have login.php page for the user to login their credentials. After the user logs in that is when the doLogin.php page will be displayed. In other words their user profile will be displayed. On the User Profile element, there is an edit button which leads them to editProfile.php page to edit their personal info. However when I clicked the back arrow on my tab to go to the User profile page back an error "Confirm Form Resubmission" was displayed. How do I counter this such that when the user wished to go back to the User Profile page, their details will be displayed?
This is my doLogin.php
session_start();
$msg = "";
//check whether session variable 'user_id' is set
//in other words, check whether the user is already logged in
if (isset($_SESSION['user_id'])) {
$msg = "You are already logged in.<br/><a href='index.php'>Home</a>";
$msg = "<a href ='logout.php'>logout</a>";
} else { //user is not logged in
//check whether form input 'username' contains value
if (isset($_POST['username'])) {
//retrieve form data
$entered_username = $_POST['username'];
$entered_password = $_POST['password'];
//connect to database
include ("dbfunctions.php");
//match the username and password entered with database record
$query = "SELECT *from role,user
WHERE user_name='$entered_username' AND
PASSWORD = SHA1('$entered_password') AND user.role_id = role.role_id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$query2 = "SELECT * FROM user,country where user.country_id=country.country_id ORDER BY `user`.`id` ASC ";
$result2 = mysqli_query($link, $query2) or die(mysqli_error($link));
$query3 = "SELECT * FROM book";
$result3 = mysqli_query($link, $query3) or die(mysqli_error($link));
if (mysqli_num_rows($result) == 1) {
$update = "UPDATE `user` SET last_login = NOW() WHERE user_name='$entered_username' ";
$resultupdate = mysqli_query($link, $update);
$row = mysqli_fetch_array($result);
$_SESSION['user_id'] = $row['id'];
$_SESSION['username'] = $row['user_name'];
$_SESSION['email'] = $row['email_address'];
$_SESSION['gender'] = $row['gender_id'];
$_SESSION['role_id'] = $row['role_type'];
$_SESSION['lastlog'] = $row['last_login'];
$msg1 = $_SESSION['username'];
$msg2 = "<b>Gender: </b> " . $_SESSION['gender'] . "<br/>";
$msg3 = "<b>Email: </b>" . $_SESSION['email'] . "<br/>";
$msg4 = "<b>Your last visit on this site: </b>" . $_SESSION['lastlog'];
$msg .= "You are logged in as " . $_SESSION['role_id'] . "<br/>";
$rowz = mysqli_fetch_array($result3);
} else { //record not found
$msg = "<p>Sorry, you must enter a valid username and password to log in.<a href='login.php'>Back</a></p>";
}
}
and this is my editProfile.php
// include a php file that contains the common database connection codes
include ("dbfunctions.php");
session_start();
$userID = $_POST['userID'];
$queryedit = "SELECT * FROM user WHERE id=$userID";
// execute the query
$resultedit = mysqli_query($link, $queryedit) or die(mysqli_error($link));
// fetch the execution result to an array
$rowedit = mysqli_fetch_array($resultedit);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="style.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.min.css" />
<script src="script.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="styles.css">
<title>Edit Profile & Settings</title>
</head>
<body>
<div class="container">
Sign Out
<div class="page-header">
<h1>OBC <small>onlinebookclub</small></h1>
<div class="row">
<div class="col-lg-6">
<form method="post" action="doSearch.php">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Go!</button>
</span>
<input type="text" class="form-control" placeholder="Title/Author/YearOfPublish">
</form>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
</div>
</div>
<!-- Registration Form - START -->
<div class="container" id="container1">
<div id='cssmenu'>
<ul>
<li class='active'><a href='#'>Profile</a></li>
<li><a href='addbook.php'>Add/Edit Books</a></li>
<li><a href='#'>Add/Edit Authors</a></li>
<li><a href='editProfile.php'>Edit Profile & Settings</a></li>
</ul>
</div>
<h2>Edit Profile</h2>
<hr>
<div class="row">
<!-- left column -->
<div class="col-md-3">
<div class="text-center">
<img src="//placehold.it/100" class="avatar img-circle" alt="avatar">
<h6>Upload a different photo...</h6>
<input type="file" class="form-control">
</div>
</div>
<!-- edit form column -->
<div class="col-md-9 personal-info">
<h3>Personal info</h3>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-lg-3 control-label">Username:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo $rowedit['user_name'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo $rowedit['email_address'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input type="hidden" name="id" value="<?php echo $rowedit['id'] ?>" />
<input type="submit" class="btn btn-primary" value="Save Changes">
<span></span>
<input type="reset" class="btn btn-default" value="Cancel">
</div>
</div>
</form>
</div>
</div>
</div>
<style>
#container1 {
background-color: #e2dada;
opacity: 0.9;
border-radius: 2em;
}
.centered-form {
margin-top: -185px;
margin-bottom: 120px;
}
.centered-form .panel {
background: rgba(255, 255, 255, 0.8);
box-shadow: rgba(0, 0, 0, 0.3) 20px 20px 20px;
}
h2{
color: orange;
}
</style>
</body>
First Way
One way of handling such errors is to redirect the page to itself.
i.e when the user logs in and when you show the doLogin page, i.e the user profile page, ry to use the header() function
header('Location:doLogin.php');
Second Way
You can make an AJAX redirect using jQuery or something