Unable to view the page after logged in - php

when I go to the page that I put the authentication code it will ask me to log in first before login. The issues are after I logged in it doesn't go to the page that wanted to go and after that clicked to the same page again it ask me to log in again. Am I did something wrong here!?
loginform.php
<div class="container">
<div class="row">
<di class="col-md-4 col-md-offset-4">
<fieldset>
<legend>Login </legend>
<form method="post" action="loginProcess.php">
<div class="form-group">
<label>User name:</label>
<input type="text" name="username" class="form-control" required>
</div>
<div class="form-group">
<label>Password:</label><input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Login" class="btn btn-default pull-right">
</div>
</form>
</fieldset>
</di>
</div>
loginProcess.php
<?php
session_start();
include ("dbCon.php");
$username = filter_has_var(INPUT_POST, 'username') ? $_POST['username']: null;
$passWD = filter_has_var(INPUT_POST, 'password') ? $_POST['password']: null;
$sql = "SELECT passwordHash FROM te_users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $passWDHash); //Get the password hash from the query results for the given username and store it in the variable indicated
if(!empty($username)){
if(!empty($passWD)){
if (mysqli_stmt_fetch($stmt)) { //Check if a record was returned by the query.
if (password_verify($passWD,$passWDHash)){
$username = $_SESSION['username'];
$login = $_SESSION['login'];
$_SESSION['login'] = true;
header("location:index.php");
}
else
{
echo "<p>Sorry, we don't seem to have that password.</p>";
}
}
else {
echo "<p>Sorry, we don't seem to have that username.</p>";
}
}
else {
echo "<p>Please enter the password.</p>";
}
}
else {
echo "<p>Please enter the username.</p>";
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
otherpage.php
this is the code that use for authentication
if( empty($_SESSION['logged_in']) )
{
header('Location:login.php');
exit;
}
else
{
}

You are doing things the wrong way round in the section that registers the successful login, and also setting a different $SESSION variable name than the one you check in your are they logged in code.
if (password_verify($passWD,$passWDHash)){
//$username = $_SESSION['username'];
//$login = $_SESSION['login'];
//$_SESSION['login'] = true;
$_SESSION['username'] = $username;
$_SESSION['logged_in'] = true;
header("location:index.php");
} else {
echo "<p>Sorry, we don't seem to have that password.</p>";
}
Also remember to start the session in any script that want to use the session
<?php
session_start();
if( empty($_SESSION['logged_in']) ) {
header('Location:login.php');
exit;
} else {
}

Related

Why is my login form not working properly

i am trying to create a basic login form for a page of mine, i haven't been coding a website for a long time so i just tried to change a bit a ready code from before, connected it to my database and the right table etc... but when i try to login it keeps failing the verify password if function saying "incorrect password"
login.php
<?php include 'includes/session.php'; ?>
<?php include 'includes/header.php'; ?>
<body class="bg-gradient-primary hold-transition login-page">
<section class="login-dark">
<?php
if(isset($_SESSION['error'])){
echo "
<div class='callout callout-danger text-center'>
<p>".$_SESSION['error']."</p>
</div>
";
unset($_SESSION['error']);
}
if(isset($_SESSION['success'])){
echo "
<div class='callout callout-success text-center'>
<p>".$_SESSION['success']."</p>
</div>
";
unset($_SESSION['success']);
}
?>
<form action="verify.php" method="POST">
<h2 class="visually-hidden">Login Form</h2>
<div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
<div class="mb-3"><input class="form-control" type="username" name="username" placeholder="Username" required></div>
<div class="mb-3"><input class="form-control" type="password" name="password" placeholder="Password" required></div>
<div class="mb-3"><button class="btn btn-primary d-block w-100" type="submit" name="login">Log In</button></div><a class="forgot" href="#">Forgot your email or password?</a>
</form>
</section>
<?php include 'includes/scripts.php' ?>
</body>
</html>
session.php
<?php
include 'includes/conn.php';
session_start();
if(isset($_SESSION['admin'])){
header('location: admin/home.php');
}
?>
verify.php
<?php
include 'includes/session.php';
$conn = $pdo->open();
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
try{
$stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM users WHERE username = :username");
$stmt->execute(['username'=>$username]);
$row = $stmt->fetch();
if($row['numrows'] > 0){
if($row['status']){
if(password_verify($password, $row['password'])){
if($row['type']){
$_SESSION['admin'] = $row['id'];
}
}
else{
$_SESSION['error'] = 'Incorrect Password';
}
}
else{
$_SESSION['error'] = 'Account not activated.';
}
}
else{
$_SESSION['error'] = 'username not found';
}
}
catch(PDOException $e){
echo "There is some problem in connection: " . $e->getMessage();
}
}
else{
$_SESSION['error'] = 'Input login credentails first';
}
$pdo->close();
header('location: login.php');
?>
do a
var_dump($row)
right before your
$_SESSION['error'] = 'Incorrect Password';
Once you know what the value of the row is, that should point you in the right direction.

checking for existing user in mysql table using php [duplicate]

This question already has an answer here:
Check to see if an email is already in the database using prepared statements
(1 answer)
Closed 2 years ago.
I have been trying this for several days now and am having problems with the code. I am trying tp learn php and mysql/MariaDB and am working on a multi user login system that allows for administrators and users.
So far I have the following working:
users can register
users can log-in and log-out if already registered (are directed to an index page based on user level
administrator is directed to "admin" home page based on admin level
administrators can create a new user from admin area (no access for user level)
only difference between registration page and the admin create user page is that the admin create user page allows the assigning the role of either user or admin (no option for this on registration page)
My problem that I am running into is that I want to add a check to prevent the duplication of user names (newly registering users or admin created users can't create a new user if name already taken). I have tried inserting a check to see but it still adds the user even if that username already exists.
I was wondering if someone could look at the code I have and see where I am going wrong.
Here is my administrator create user code:
<?php include('../functions.php') ?>
if (!isAdmin()) {
$_SESSION['msg'] = "You must log in first";
header('location: ../login.php');
}
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL - Create user</title>
<link rel="stylesheet" type="text/css" href="../style.css">
<style>
.header {
background: #003366;
}
button[name=register_btn] {
background: #003366;
}
</style>
</head>
<body>
<div class="header">
<h2>Admin - create user</h2>
</div>
<form method="post" action="create_user.php">
<?php echo display_error(); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>User type</label>
<select name="user_type" id="user_type" >
<option value=""></option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="register_btn"> + Create user</button>
</div>
</form>
</body>
</html>
**Here is Register page:**
<?php include('functions.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php echo display_error(); ?>
<div class="input-group">
<label for="username" class="col-md-3 control-label">User Name*</label>
<div class="col-md-9">
<input type="username" class="form-control" name="username" placeholder="User Name" required>
</div>
</div>
<div class="input-group">
<label for="email" class="col-md-3 control-label">Email*</label>
<div class="col-md-9">
<input type="email" class="form-control" name="email" placeholder="Email" required>
</div>
</div>
<div class="input-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="password_1" placeholder="Password" required>
</div>
</div>
<div class="input-group">
<label for="password" class="col-md-3 control-label">Confirm password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="password_2" placeholder="Password" required>
</div>
</div>
<div class="input-group">
<button type="submit" class="btn" name="register_btn">Register</button>
</div>
<p>
Already a member? Sign in
</p>
</form>
</body>
</html>
Here are all my functions:
<?php
session_start();
// connect to database
$db = mysqli_connect('removed variables to connect to database this works');
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
function register(){
// call these variables with the global keyword to make them available in function
global $db, $errors, $username, $email;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
$sql= "SELECT * FROM users WHERE username = '$username'";
$result=mysqli_query($sql);
if(mysqli_num_rows($result)!=0)
{
echo"name already exists";
}
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = hash('sha256', $password_1);//encrypt the password before saving in the database
// excecute insert query
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created!!";
header('location: home.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
}
// ge
// return user array from their id
function getUserById($id){
global $db;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
// log user out if logout button clicked
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
header("location: login.php");
}
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
// LOGIN USER
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$password = hash(sha256, $password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
The function I have been adding the code to is the register function As you can see, I selected all from my users table and assigned it to a variable (the username variable was assigned just above it from the Post Action. I then did a mysqli query on that variable and assigned this to another variable. Then I tried to say if the number of rows did not equal zero, then the username existed.
I am not sure what I am doing wrong. If any can provide some insight, please let me know. I know this code is probably not the best. I am trying this out in my local environment to learn. Any advice would be greatly appreciated.
Thanks in advance.
The propblem is in the mysqli_query function, this function needs at least 2 parameters, the first one is the link to your database, so your code should be something like:
$connection = mysqli_connect("localhost","db_user","db_password","db_name");
/* your code */
$result=mysqli_query($connection, $sql);

login and register in php not responding

i have a website for users to login and register, the website was working fine when login and register was in 2 different pages, now i have made them both in the same page, the html code is like below:
<h2>Login</h2>
</div>
<form method="post" class="form-detail" action="index.php">
<?php include('errors.php'); ?>
<div style="padding-right: 20px; margin-left: -40px;" class="input-group">
<label>Username</label>
<input type="text" name="username" >
</div>
<div style="padding-right: 20px; margin-left: -40px;" class="input-group">
<label>Password</label>
<input type="password" name="password">
</div>
<div class="input-group">
<button type="submit" class="btn" name="login_user">Login</button>
</div>
</form>
</div>
<form class="form-detail" method="post" action="index.php">
<div class="header">
<h2>Register Now</h2>
</div>
<?php include('errors.php'); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
the server.php file which does the functionality is like:
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'teia');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: profile.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
and finally the error.php is below
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
earlier it was working completely fine, now when i added both login and register in same pages, both login and register not working, instead simply loading the page, as i am new to php, can anyone please tell me whats wrong with my code
You can use switch statement for your solutions with different submit button value like below
<button type="submit" class="btn" value="login">Login</button>
<button type="submit" class="btn" value="register">Register</button>
<?php
switch($_POST['submit']) {
case 'login':
//...
break;
case 'register':
//...
break;
}
?>
The problem is that both your form actions point to index.php which isn't where the functionality is.
<form method="post" class="form-detail" action="server.php">
Change both forms to this. That should solve your problem.
Edit:
To display the errors, you'll need access to the $errors variable you defined. One way to do this is to move the code in error.php like so:
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
} else {
include('errors.php');
}
Are you sure; you are adding this <?php include('server.php'); ?> at the top of the index.php page?

Logout - have to hit button twice for it to work?

Trying to perform a logout from current page. Basically if you hit the logout, it will just show the login form again. I do not want to call a page doing this. When I execute the "Logout" button, it still shows the user logged in, but if I hit the "Logout" button a second time it works correctly. Or if I refresh the page it works also. Just seems the initial submitting of "Logout" does not refresh.
<?
session_start();
$subtitle="Login";
ob_start();
// require("header2.php");
//Get any form data.
$football->WhoOnlineDelete;
$username=$_POST['username'];
$password=$_POST['password'];
global $conn;
$conn = mysqli_connect("localhost","","", "");
function logOut()
{
unset($_SESSION['user']);
unset($_SESSION['uname']);
session_destroy();
ob_start();
exit();
}
if ($_POST)
{
//Make sure cookies are enabled.
// if ($_COOKIE["football"]=="")
// {
// $football->ErrorMessage("You must use a browser that supports cookies and<br> have them enabled in order to access this site.");
// }
// else
// {
//Check input.
if ($username=="")
{
echo "Please enter a username.";
}
elseif ($password=="")
{
echo"Please enter your password.";
}
else
{
//Verify the password and redirect to default page if correct.
$sql=mysqli_query($conn, "select * from phpfb_users where user = '".$username."'");
$row = mysqli_fetch_object($sql);
$rows = mysqli_num_rows($sql);
if($rows == 0)
{
echo "User '".$username."' not found.";
}
elseif (md5($password) != $row->password)
{
echo "Incorrect password, please reenter.";
}
else
{
$user=$row->user;
if ($row->name =="") {
$uname=$row->user;
} else {
$uname=$row->name;
}
$_SESSION['uname'] = $uname;
$_SESSION['user'] = $user;
header("Location: loginJERRY.php");
}
}
}
//}
else
{
//Set test cookie.
setcookie("football","peanutbutter",0,"/",$football->domain,0);
}
?>
<div>
<div style="display:block;margin:0px auto;" background-color="lightblue;">
<?php if(empty($_SESSION["user"])) { ?>
<form name="loginform" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<div class="error-message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="field-group">
<div><label for="login">Username: </label>
<input name="username" type="text" class="input-field">
<label for="password">Password:</label>
<input name="password" type="password" class="input-field">
<input type="submit" name="login" value="Login" class="form-submit-button"></span></div>
</div>
</form>
<?php
} else {
$result = mysqli_query($conn,"SELECT * FROM phpfb_users WHERE user='".$username."' and password = '".$password."'");
$row = mysqli_fetch_array($result);
?>
<br><br>
<form action="" method="post" id="frmLogout">
<div class="member-dashboard">Welcome <?php echo $user; ?>, You have successfully logged in!
<input type="submit" name="logout" value="logout" class="logout-button"></div>
</form>
<?
if (isset($_POST['logout'])) {
if ($_POST['logout'] == 'logout') {
logOut();
} else if ($_POST['logout'] != 'logout') {
}
}
?>
</div>
</div>
<?php } ?>
</body>
<script type='text/javascript'>
document.loginform.username.focus();
document.loginform.username.select();
</script>
Am I missing something?
You need to check logout functionality before you html page renders, so add you logout key in $_POST after logout() function like,
<?
..........
$conn = ....
function logOut()
{
unset($_SESSION['user']);
unset($_SESSION['uname']);
session_destroy();
ob_start();
exit();
}
if (isset($_POST['logout']) && $_POST['logout'] == 'logout') {
logOut();
} // not required else part here
if($_POST) {
....
?>
From the technical point of view the user is logged out (because the session variable is destroyed) but the page is showing something different. You need to take the logout part on top before the page gets rendered, otherwise the page doesn't know that the user is logged out:
<?
session_start();
$subtitle="Login";
ob_start();
// require("header2.php");
//Get any form data.
$football->WhoOnlineDelete;
$username=$_POST['username'];
$password=$_POST['password'];
global $conn;
$conn = mysqli_connect("localhost","","", "");
function logOut()
{
unset($_SESSION['user']);
unset($_SESSION['uname']);
session_destroy();
ob_start();
exit();
}
if (isset($_POST['logout'])) {
if ($_POST['logout'] == 'logout') {
logOut();
} else if ($_POST['logout'] != 'logout') {
}
}
if ($_POST)
{
//Make sure cookies are enabled.
// if ($_COOKIE["football"]=="")
// {
// $football->ErrorMessage("You must use a browser that supports cookies and<br> have them enabled in order to access this site.");
// }
// else
// {
//Check input.
if ($username=="")
{
echo "Please enter a username.";
}
elseif ($password=="")
{
echo"Please enter your password.";
}
else
{
//Verify the password and redirect to default page if correct.
$sql=mysqli_query($conn, "select * from phpfb_users where user = '".$username."'");
$row = mysqli_fetch_object($sql);
$rows = mysqli_num_rows($sql);
if($rows == 0)
{
echo "User '".$username."' not found.";
}
elseif (md5($password) != $row->password)
{
echo "Incorrect password, please reenter.";
}
else
{
$user=$row->user;
if ($row->name =="") {
$uname=$row->user;
} else {
$uname=$row->name;
}
$_SESSION['uname'] = $uname;
$_SESSION['user'] = $user;
header("Location: loginJERRY.php");
}
}
}
//}
else
{
//Set test cookie.
setcookie("football","peanutbutter",0,"/",$football->domain,0);
}
?>
<div>
<div style="display:block;margin:0px auto;" background-color="lightblue;">
<?php if(empty($_SESSION["user"])) { ?>
<form name="loginform" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<div class="error-message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="field-group">
<div><label for="login">Username: </label>
<input name="username" type="text" class="input-field">
<label for="password">Password:</label>
<input name="password" type="password" class="input-field">
<input type="submit" name="login" value="Login" class="form-submit-button"></span></div>
</div>
</form>
<?php
} else {
$result = mysqli_query($conn,"SELECT * FROM phpfb_users WHERE user='".$username."' and password = '".$password."'");
$row = mysqli_fetch_array($result);
?>
<br><br>
<form action="" method="post" id="frmLogout">
<div class="member-dashboard">Welcome <?php echo $user; ?>, You have successfully logged in!
<input type="submit" name="logout" value="logout" class="logout-button"></div>
</form>
</div>
</div>
<?php } ?>
</body>
<script type='text/javascript'>
document.loginform.username.focus();
document.loginform.username.select();
</script>
You could also reload the page after calling the logout function, but this isn't very nice in my opinion. You always have to keep in mind that you first have to execute all the logic before you render the page.

Cant log in with right info, page just refreshes

Heres the issue, I am trying to login with the correct info (triple checked through phpmyadmin) but all it is doing is redirecting back to the login page like the info is not right.
Login Form (at the top of page)
<?php
session_start();
include "includes/class.users.php";
if(isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$users->login($email, $password);
}
?>
Login Form
<form method="POST" action="" name="login">
<div id="wrappermiddle">
<h2>Login</h2>
<div id="username_input">
<div id="username_inputleft"></div>
<div id="username_inputmiddle">
<input name="email" type="text" id="myusername" placeholder="Email Address">
<img id="url_user" src="./images/mailicon.png" alt="">
</div><!--ends username_inputmiddle-->
<div id="username_inputright"></div>
</div><!--ends username_input-->
<div id="password_input">
<div id="password_inputleft"></div>
<div id="password_inputmiddle">
<input name="password" type="password" id="mypassword" placeholder="Password">
<img id="url_password" src="./images/passicon.png" alt="">
</div><!--ends password_inputmiddle-->
<div id="password_inputright"></div>
</div><!--ends password_input-->
<div id="submit">
<input type="image" src="./images/submit.png" name="login" value="Login">
</form>
class.users.php
<?php
include "class.database.php";
class Users extends Database {
public function login($email, $password) {
$stmt = $this->mysqli->prepare("SELECT email, password FROM members WHERE email = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->bind_result($email, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
session_start();
$_SESSION['loggedin'] = true;
header("Location: dashboard.php");
}
} else {
return false;
}
$stmt->close();
$stmt->free_result();
}
}
$users = new users();
?>
dashbord.php at the top
<?PHP
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
} else {
header ("Location: index.php");
}
?>
EDIT - I tried loggin in with a bad password and I get the error - There is an error
When I login with the correct info, if just refreshes the login page.
I think the problem is you're setting the header after some html has been rendered.
My approach would be to include in the Login page
if ($_SESSION['loggedin] = true) {
header("Location: dashboard.php");
} else {
login page
}

Categories