Session id is set even after logout - php

I'm trying to use session to keep the access to my website only to the authorized users.
Now, This is my main page:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
require 'dbConfigBDO.php';
require 'message.php';
require 'SafeRedirect.php';
if (isset($_POST['username']) AND isset($_POST['pass']))
{
$_SESSION['message'] = '';
$username = $_POST['username'];
$password = $_POST['pass'];
$response= $conn->prepare('SELECT username,pass
FROM AdminTable
WHERE username = :nom
');
$response->bindValue(':nom',$username,PDO::PARAM_STR);
$response->execute();
$member = $response->Fetch();
$response->CloseCursor();
if(!$member) exit('اسم المستخدم غير صحيح');
if($password !== $member['pass']) exit('كلمة المرور غير صحيحه');
$_SESSION['id'] = $member['username'];
$_SESSION['message'] = htmlspecialchars($user). ' تم تسجيل دخولك بنجاح ';
safe_redirect('index.php');
exit;
}
?>
<!-- Log in:
First read name and password:-->
<form action="" method="post" id="form">
<fieldset class="form-item">
<legend>الدّخول</legend>
<label for="email">الاسم</label><input type="text" name="username" id="username"><br>
<label for="pass">كلمة المرور</label><input type="password" name="pass" id="pass">
</fieldset>
<fieldset class="form-submit">
<input type="submit" value="موافق">
</fieldset>
</form>
</body>
</html>
the problem here is when I redirect the user to index.php which checks as follows:
<?php
session_start();
require 'message.php';
require 'SafeRedirect.php';
$_SESSION['message'] = '';
$session_id = (isset($_SESSION['id'])) ? $_SESSION['id'] : null;
if($session_id == null)
{
$_SESSION['message'] = htmlspecialchars($user). ' Please sign in first... ';
safe_redirect('login.php');
exit;
}
?>
<a href="logout.php">
click here to log out</a>
Now when I press logout I shouldn't be able to access page index.php right?
the problem is I still can!
I tried to print the session ID and it does not change even after logout. I used
<?php
require 'SafeRedirect.php';
session_start();
unset($_SESSION["id"]);
session_regenerate_id(true);
session_destroy();
safe_redirect('login.php');
?>
my code use to work long time ago on another website but not now and I'm really confused what I did change since then.

Related

Login issue after logging out

I'm currently working on a login page for my website and I'm using PHP.
When I try to login for the first time, it works just fine, passwords are verified correctly, it shows an error if the password doesn't match or if the user is not registered first (email address not found), so I'm thinking the code logic is fine.
When I logout and try to login again, the code doesn't work as it should, I'm just redirected to the login page regardless if I type the password right or wrong or if the email address exists. Everything works fine again after I close the tab and reopen it.
I think it may be a session issue but I'm still new to this so I hope you can help me.
This is the logout code (edited):
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
session_cache_expire();
session_unset();
session_destroy();
header ('Location: home.php');
?>
</html>
Login:
<?php
if(!isset($_SESSION)) {
session_start();
}
var_dump($_SESSION);
if(isset($_SESSION["userID"])){
header("Location: home.php");
}
require('dbconnect.php');
?>
<!DOCTYPE html>
<html>
<head>
<title> Business Bridge </title>
</head>
<body>
<div id="content">
<h2> Logge Dich ein </h2>
<?php
if(isset($_GET['login'])){
$email = $_POST['email'];
$passwort = $_POST['passwort'];
$statement = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$statement ->bindParam(1,$email);
$result = $statement->execute();
$res = $statement->fetch();
$data = $res[1] ."\n" . $res[2] . "\n";
if($statement->rowCount() > 0 ) {
if (password_verify($passwort, $res[2]) && $email == $res[1]){
$_SESSION['email'] = $_POST['email'];
$_SESSION['vname'] = $_POST['vname'];
$_SESSION['userlevel'] = $res[6];
$_SESSION['userID'] = $res[0];
header('Location: home.php');
}
else{
echo "Falsches Passwort, probiere es noch einmal!";
}
}else{
echo "Die Email Addresse gibt es nicht!";
}
}
?>
<form action="?login=1" method="post">
E-Mail: <br> <input type="email" size="40" maxlength="250"
name="email"><br><br>
Dein Passwort:<br> <input type="password" size="40"
maxlength="250" name="passwort"><br><br>
<input id="button" type="submit" value="Send">
</form>
</div>
</div>
</body>
</html>
<?php
$pdo->connection = null;
?>
Edit: The problem was caused by a false redirection. The logout code would redirect to a different login page.
//Try this one in your logout.php page
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

PHP session variable won't change

UPDATE : I added all codes;
I want to create a login page for test purpose and I included attempt number with php sessions. The problem is session's variable isn't changing.
index.php
<?php
if (!isset($_SESSION)) {
session_start();
$_SESSION['attempt']=3;
}
if ($_SESSION['attempt']<0){
header('location:login_error.php');
}
require('../function/start.php');
$title = 'Login';
require('../template/header.php');
$ip = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
var_dump($_SESSION['attempt'])
?>
<h3 class="epad_header">Login</h3>
<div id="epad_wrapper">
<div id="ad_form_wrapper">
<form action="control.php" method="POST">
<fieldset>
<span class="formtext">ID</span>
<input type="text" name="epadName" id="epadName" required>
<span class="formtext">Pass</span>
<input type="password" name="epadPass" id="epadPass" required>
<input type="submit" value="Ok" class="formbuton" name="formbuton">
<br>
<span class="formtext">IP Adress : <?php echo $ip; ?></span>
<br>
<span class="formtext">Attempt : <?php echo $_SESSION['attempt'] ?></span>
</fieldset>
</form>
</div>
</div>
<?php require('../template/footer.php'); ?>
control.php
<?php
if (!isset($_SESSION)) {
session_start();
}
require('../function/start.php');
$title = 'Control';
if (isset($_POST['formbuton'])){
$name = htmlentities($_POST['epadName']);
$pwd = htmlentities($_POST['epadPass']);
}
$check = $db->prepare('SELECT user, pass FROM users');
$check->execute();
$result = $check->fetch(PDO::FETCH_ASSOC);
$user = $result['user'];
$pass = $result['pass'];
if ($name == $user && $pwd == $pass ){
$_SESSION['name']= $name;
header("location:main.php");
}else{
$_SESSION['attempt']--;
header('location:index.php');
}
?>
when a user enter the page(first visit) ; a session will be started, and attempt variable will be created. (index.php)
If they enter false data attempt variable will be decreased. (control.php)
if there are 3 failed attempt page will redirects to login_error.page (index.php)
First Problem : Session variable is not changing.
Second Problem: Even If I enter correct data, the page directs to index.php (login area) instead of main.php
try to place session_start(); at the first line, after <?php
I've solved the problem;
Actually I don't understand why
if(!isset($_SESSION){session_start; $_SESSION['attempt']=3;}
didn't work but when I modified this code to that code
session_start;
if (!isset($_SESSION['attempt']){$_SESSION['attempt']=3;}
Anyway, thank you for reading.

Header function is redirecting to index.php instead of the specified file (PHP)

I am currently organising my files into appropriate folders and a problem has arisen. Before changing the code to organise the files everything worked. Now whenever I try to log in, instead of redirecting to 'Staff/staff.php', it redirects to 'Staff/index.php'.
The code is as follow:
<?php
session_start();
include("connectdb.php");
//if the form has been submitted
if (isset($_POST['submitted'])){
//get the information out of get or post depending on your form
$username = $_POST['username'];
$password = $_POST['password'];
global $db;
//sanitise the inputs!
$safe_username = $db->quote($username);
//run a query to get the user associated with that username
$query = "select * from user where username = $safe_username";
$result = $db->query($query);
$firstrow = $result->fetch(); //get the first row
if (!empty($firstrow)) {
//check the passwords, if correct add the session info and redirect
$hashed_password = md5($password);
if ($firstrow['password'] == $hashed_password){
$_SESSION['id'] = $firstrow['userID'];
$_SESSION['username'] = $firstrow['username'];
$_SESSION['fname'] = $firstrow['first_name'];
$_SESSION['lname'] = $firstrow['last_name'];
$_SESSION['staff'] = $firstrow['staff'];
if($firstrow['staff'] == 1) {
header("Location:Staff/staff.php");
exit();
} else {
//echo "Success!";
header("Location:Customer/customer.php");
exit();
}
} else {
echo "<h1>Error logging in, password does not match</h1>";
}
} else {
//else display an error
echo "<h1>Error logging in, Username not found</h1>";
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="CSS/theme.css">
</head>
<body>
<h1 class="register-title">Aston Animal Sanctuary</h1>
<div class="register">
<!--<form method="link" action="staff.php">
<input type="submit" value="Staff Login">
</form>-->
<form action="index.php" method="post">
<input type="text" class="register-input" name="username" placeholder="Username">
<input type="password" class="register-input" name="password" placeholder="Password">
<input type="submit" value="Login" class="register-button">
<input type="hidden" name="submitted" value="TRUE" />
</form>
<form method="link" action="register.php">
<input class="register-button" type="submit" name="register" value="Register">
</form>
<div>
<!--Test-->
</body>
</html>
<?php include('View/footer.html'); ?>
Is the header the problem?
EDIT
The same thing happens with my logout file. It redirects to 'Staff/logout.php' instead of '../logout.php'. It worked before I started organising the files.
The code for logout.php:
<?php
session_start(); //get the previous session info
session_destroy(); //destroy it
header("Location: ../index.php"); //redirect back to the start
?>
Have you tried:
header("Location: ./staff/staff.php");
and:
header("Location: ./customer/customer.php");

Variable $_SESSION does not want to be setted

So this is the code for page index.php: the $_SESSION["username"] variable seems to be not setted and I dunno why becuase in the login page I am using the isset control and the login is successful if I'm entering the right values;it is not if I am entering wrong username and password. I know I should "code" the password with md5 but right now that is not my problem :(
As you can see I'm redirecting to the index page after the login. From the index page I'm redirecting to the "home.php" page if the user already logged in. The problem is that after been doing the login,it keeps showing the login form and it is not redirecting me to home.php..
<?php session_start();
require_once "dbConn.php"; dbconnect();
if(isset($_SESSION["username"])){
echo $_SESSION["username"]; // TEST it never enters THERE!!!
echo'<p>Trasferimento alla home page</p>';
header("Refresh: 2; URL = home.php");
}
else{
echo'<div id=\"container\">';
echo'
<div id=\"content\">
<h2> You need to login :</h2>
<br/>
<form id="form1" name="form1" method="post" action="login.php">
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="submit" name="accedi" id="accedi" value="Accedi" />
</form>
<br/>
</div>';
include 'Footer.php';
echo'</div>';
}?>
And this is the login.php page:
<?php
require_once "dbConn.php"; dbconnect();
if(isset($_POST['username']) && isset($_POST['password'])) {
$username=mysql_real_escape_string($_POST['username']);
$pwd = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM user WHERE username='$username' AND password ='$pwd';");
if(mysql_num_rows($query) == 1){
$sessione =mysql_fetch_array($query);
$_SESSION["username"] = $sessione["username"];
echo $_SESSION["username"]; //TEST - it prints what I want: my username
$_SESSION["logged"] = true;
echo'Login effettuato con successo!';
header("Refresh: 2; URL = index.php");
}
else if((mysql_num_rows($query) == 0)){
echo'Utente non registrato o password errata';
header("Refresh: 2; URL = index.php");
}
}
?>
Thx all ;)
You forgot to call session_start() on your login page
<?php
require_once "dbConn.php"; dbconnect();
should be
<?php
session_start()
require_once "dbConn.php"; dbconnect();

PHP login system without a database, sessions is not working?

First of all I won't build a login system that uses a database, I know it's more secure but in this case it's not relevant...
I have three files login.php, admin.php and config.php. The users email and password is stored in variables in config.php. If the user is logging in a session should be set. Then if a user that hasn't logged in trying to access admin.php ":-(" should be printed. But now the ":-(" is always printed and something needs to be wrong with how I coded it all...
config.php:
<?php
//site data
$title = "Abbesplace";
$siteurl = "index.php";
//user data
$password = "testtest";
$email = "example#example.com";
$name = "Albin Larsson";
?>
login.php:
<?php
require_once("config.php");
if (($_POST['email'] == $email && $_POST['password'] == $password)) {
//login
session_start();
$_SESSION['logged']= "welcometomoon";
header("Location: admin.php");
} else {
echo "login faild";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
</head>
<body>
<div>
<form method="post" action="login.php">
Email:<input type="email" name="email"/>
Password:<input type="password" name="password"/>
<input type="submit"/>
</form>
</div>
</body>
</html>
admin.php:
<?php
if(isset($_SESSION['logged'])){
echo "Hello";
} else {
echo ":-(";
}
?>
Any suggestions on what I should make different?
(I'm a newbie when i comes to PHP)...
You have to call session_start on every page. Right now you are only calling it when you post to the login form.

Categories