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

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.

Related

Unable to view the page after logged in

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 {
}

my login form always access denied

I created a simple login form. When I enter the correct username and password, it is always displaying the access denied message.
verify.php:
<?php
session_start();
$conn = mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($conn,'maindata') or die(mysqli_error($conn));
$uname=$_POST['username'];
$pass=$_POST['password'];
$password = md5($pass);
$result = mysqli_query($conn,"select * from users where username='$uname' and password='$password'")
or die("Could not execute the select query.");
$row = mysqli_fetch_assoc($result);
if(is_array($row) && !empty($row))
{
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
}
else
{
echo "<center></h1>Access Denied</h1></center>"."<br />";
echo "<center></h6>Please wait while you are redirected in 3 seconds</h6></center>"."<br />";
header('Refresh: 3; url=login.html');
}
if(isset($_SESSION['valid']))
{
header("Location:index.html");
}
login.html:
<?php
session_start();
if(isset($_SESSION['valid'])){
header("Location:index.html");
}
else
{
header("location:login.html");
}
?>
<form method="post" action="verify.php" class="login" class="contact_form">
<p>
<label for="login">Email:</label>
<input type="text" name="username" placeholder = "Enter Username Here...">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" placeholder = "*******">
</p>
<p class="login-submit">
<button type="submit" class="login-button">Login</button>
</p>
<p class="forgot-password">Forgot your password?</p>
</form>
You'r code loops it self, Login.html checks if a user is logged in ( which they arrent because they cant login ) and redirects them from Login.html to Login.html meaning that you never enter your php code. You should not check if the user is already logged in when trying to access the login page.
Also you should consider making a file to check if the user is logged in, it could be something like this:
checkloggedin.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if($_SESSION['loggedin'] == false)
{
die(header("Location: ./index.php"));
}
?>
When you need to check if a user is logged in you can just start your pages off with:
<?php
include"checkloggedin.php"
?>

PHP: this webpage has a redirect loop

I know this error is very common and plenty of solution are mentioned but for some reason I cant get it working.
This is my index.php file which is the log in page for users
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: index.php");
}
?>
...
...
<form name='log' action='loginproc.php' method='POST'>
<input type="text" placeholder="Username" name="username">
<input type="password" placeholder="Password" name="password">
<input type='submit' value='Login' onclick="return check()">
</form>
This is the loginproc.php file
<?php
require 'config.php';
require 'core.inc.php';
if(isset($_POST['username'])&&isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(!empty($username) && !empty($password)) {
// $md5pwd = md5($password);
$query = "SELECT username FROM `login` WHERE `username` = '$username' and `password` = '$password';";
//echo $query;
//$query_run = mysqli_query($query);
//echo $query_run;
if($query_run = mysqli_query($conn,$query)) {
//echo $query_run;
$query_num_rows = mysqli_num_rows($query_run);
if($query_num_rows==0) {
phpAlert( "Invalid USERNAME or PASSWORD combination" );
echo '<script type="text/javascript">window.location = "index.php"</script>';
exit();
//echo '<p> Invalid USERNAME or PASSWORD combination <br /><br /> Click here to Login ';
}
else if($query_num_rows==1) {
//echo 'Hello';
$_SESSION['username']=$username;
header('Location: main.php');
}
}
}
else {
echo 'You Must supply a username and password';
}
}
function phpAlert($msg) {
echo '<script type="text/javascript">alert("' . $msg . '")</script>';
}
?>
The core.inc.php file
<?php
ob_start();
session_start();
function loggedin() {
if(isset($_SESSION['username'])&& !empty($_SESSION['username'])) {
return true;
}
else {
return false;
}
}
?>
you need to add an extra parameter when redirecting to index.php.
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
if($_REQUEST['ftime']!=1)
{
header ("Location: index.php?ftime=1");
}
}
?>
You need to have the redirect go elsewhere for logged in users and bypass when not logged in:
<?php
session_start();
// if session username is set and valid, go to somewhere else
if(isset($_SESSION['username']) && !empty($_SESSION['username'])) {
// elswhere could be a profile page, or similar
header("Location: elsewhere.php");
// It is more accepted to exit after a header
exit;
}
?>
<!-- All other instances beside valid login will allow this to form to show-->
<form name='log' action='loginproc.php' method='POST'>
<input type="text" placeholder="Username" name="username">
<input type="password" placeholder="Password" name="password">
<input type='submit' value='Login' onclick="return check()">
</form>

It seem not fetch the $_POST

I'm stuck in login page. From home,user will login (form send to check_login) and from check_login user will be directed to page based on their role. However, I cannot pass through the login page. I mean I keep getting the error message from header('location: 1.php?error=1');
fyi, i've successfully connected to db. The data is there. But if I echo oci_num_rows, the result is 0..
Here is my code login.php
<form action="check_login.php" method="post" name="login">
<div class="error"><?php include('error-handler.php'); ?></div>
<p> Matric / Staff ID :</p>
<p><input type="text" name="id" size="20" maxlength="10" onkeypress="return isNumberKey(event)" required value=""/></p>
<p>Password :</p>
<p><input type="password" name="password" id="password" size="20" maxlength="8" min="6" required value="" />
<script type="text/javascript">
//add a show password checkbox
new ShowPasswordCheckbox(document.getElementById("password"));
//test the submitted value
document.getElementById('login').onsubmit = function()
{
alert('pword = "' + this.pword.value + '"');
return false;
};
</script>
</p>
<p><input type="submit" name="submit" value="Login"/></p> </form>
and here is my check_login.php
<?php
ob_start();
// Inialize session
session_start();
require_once('connection.php');
//if the login form is submitted
if(isset($_POST['submit']) && !empty($_POST['submit']))
{
$id = $_POST['id'];
$pass = $_POST['password'];
$stmt2= oci_parse($conn, "SELECT * FROM user1 WHERE id = '$id'")or die(oci_error());
$check2 = oci_execute($stmt2);
//Gives error if user dosen't exist
$check3 = oci_num_rows($stmt2);
if ($check3 == 0)
{
header('location: 1.php?error=1'); //the msg will be: you are not eligible user.
exit();
}
else
{
while($info2=oci_fetch_array($stmt2,OCI_ASSOC+OCI_RETURN_NULLS))
{
//gives error if the password is wrong
if ($pass != $info2['password'])
{
header('location: 1.php?error=2'); //password mismatch with id
exit();
}
else
{
// if login is ok then we add a cookie
$_SESSION['id'] = $_POST['id'];
$_SESSION['password'] = $_POST['password'];
$hour = time() + 86400;
setcookie(ID_site, $_SESSION['id'], $hour);
setcookie(Pass_site, $_SESSION['password'], $hour);
//then redirect them to the members area
if ($info2['role']=='admin')
{
header('Location: homeAdmin.php');
}
elseif ($info2['role']=='staff')
{
header('Location: homeStaff.php');
}
elseif ($info2['role']=='student')
{
header('Location: homeStudent.php');
}
else
{
header('Location: 1.php');
}
} //end else
} //end while
}//end else
}// end if submit
else
{
header('Location: 1.php');
}
?>
Please share your opinion or pls correct if i'm wrong. Thank you. :)
From PHP manual 'oci_num_rows' : http://php.net/manual/en/function.oci-num-rows.php
This function does not return number of rows selected! For SELECT
statements this function will return the number of rows, that were
fetched to the buffer with oci_fetch*() functions.

How can I split my Login process into functions?

I'm currently using a modified version of a login script I found online.
Can anybody suggest some ways of modularizing the code into functions?
Here is the code for the login page:
<?php
include("db.php");
include("login_fns.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$password=md5($password);
$sql="SELECT * FROM client_login WHERE Username='$username' and Password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row = mysql_fetch_array($result);
$client_ref = $row['Client_ref'];
$user_level = $row['user_level'];
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['user_level'] = $user_level;
$_SESSION['client_ref'] = $client_ref;
$_SESSION['user'] = $username;
if ($user_level == '1') {
header('Location: admin.php');
} else {
header('Location: myaccount.php');
}
}
else
{
echo "Error logging in!";
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>
Ideally, I'd like a function for the user account search and the session setting. I previously tried to copy snippets of this code into a separate php functions file, but it didn't seem to work.
What do you think about this? :)
The function
<?php
function checkLogin($username, $password) {
global $bd;
$returnArray=array();
$username=mysqli_real_escape_string($bd, $username);
$password=md5($password);
$getUser=mysqli_query($bd, "SELECT `Client_ref`,`user_level` FROM client_login WHERE Username='$username' and Password='$password'");
$arrayUser=mysqli_fetch_array($getUser);
if(mysqli_num_rows($getUser) == 0)
{
$returnArray['error']='true';
$returnArray['errormsg']='User not found in the database.';
return $returnArray;
}
$returnArray['Client_ref']=$row['Client_ref'];
$returnArray['user_level']=$row['user_level'];
return $returnArray;
}
?>
Rest of the code
<?php
include("db.php");
include("login_fns.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=$_POST['username'];
$password=$_POST['password'];
$loginArray=checkLogin($username, $password);
if(!isset($loginArray['error']))
{
$_SESSION['user_level'] = $loginArray['Client_ref'];
$_SESSION['client_ref'] = $loginArray['user_level'];
$_SESSION['user'] = $username;
if($loginArray['user_level'] == '1')
{
header('Location: admin.php');
}
else
{
header('Location: myaccount.php');
}
}
else
{
echo "Error logging in!";
echo "The detailed error message is: ".$returnArray['errormsg'];
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>

Categories