Session are not working - php

Hello i have created login system but its not working for some reason , i start session after some one login and then made some check if session are isset and if session are no more then 1 hour :
this is my login script on index.php :
<?php
require 'mysql.php';
if(isset($_SESSION["username"]) && time() - $_SESSION["CREATED"] > 3600){
session_start();
session_unset();
session_destroy();
}
if(isset($_SESSION["username"]) && time() - $_SESSION["CREATED"] < 3600){
header('Location: main.php');
}
if (isset($_POST["login"])){
$username = $_POST["username"];
$password = $_POST["password"];
$stmt = $connect->prepare("SELECT username, password FROM users WHERE username=? ");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$rowcount = $result->num_rows;
if ($rowcount > 0){
while ($row = $result->fetch_assoc()) {
if ($row["username"] == $username && $row["password"] == $password){
if(!isset($_SESSION)) {
session_start();
}
$_SESSION["username"] = $username;
$_SESSION["usertype"] = $row["usertype"];
$_SESSION["userid"] = $row["id"];
$_SESSION["CREATED"] = time();
header('Location: main.php');
} else {
$error_msg2 = "Username or password does not mach";
$error2 = "error";
}
}
} else {
$error_msg2 = "No such user";
$error2 = "error";
}
echo $error_msg2;
$stmt->close();
$connect->close();
}
?>
and this is main.php code :
if(isset($_SESSION["username"]) && time() - $_SESSION["CREATED"] > 3600){
session_start();
session_unset();
session_destroy();
header('Location: index.php');
}
so ones you login you will by redirected to main.php and if session are set u should be unable to access index.php cuz if you will try u and session are not expired you will get redirected back you main.php same with main if session are expired you will get redirected back to index.php to login , but no matter if you are logged in or no you can walk between them freely

You should call session_start in any case - it fills $_SESSION with values. Also it's enough to unset $_SESSION['username'], no need to destroy whole session - PHP can take care of that. Here is code that should work:
index.php
<?php
require 'mysql.php';
session_start();
if (isset($_SESSION['username'])) {
if ($_SESSION['CREATED'] < 3600) {
header('Location: main.php');
exit;
}
unset($_SESSION['username']);
}
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $connect->prepare('SELECT username, password FROM users WHERE username=? LIMIT 1');
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$rowcount = $result->num_rows;
if ($rowcount > 0) {
$row = $result->fetch_assoc();
if ($row['username'] == $username && $row['password'] == $password) {
$_SESSION['username'] = $username;
$_SESSION['usertype'] = $row['usertype'];
$_SESSION['userid'] = $row['id'];
$_SESSION['CREATED'] = time();
header('Location: main.php');
exit;
} else {
$error_msg2 = 'Username or password does not mach';
$error2 = 'error';
}
} else {
$error_msg2 = 'No such user';
$error2 = 'error';
}
echo $error_msg2;
$stmt->close();
$connect->close();
}
main.php
session_start();
if (!isset($_SESSION['username']) || time() - $_SESSION['CREATED'] > 3600){
unset($_SESSION['username']);
header('Location: index.php');
exit;
}

You have to call session_start() before you can use $_SESSION.
<?php
require 'mysql.php';
session_start();
if(isset($_SESSION["username"]) && time() - $_SESSION["CREATED"] > 3600){
session_unset();
session_destroy();
}

I have a suggestion. Create a session validation function.
function sessionValidate($username,$id=NULL)
{
$status = session_status();
if($status == PHP_SESSION_NONE)
{
//There is no active session
session_start();
}
if(!isset($_SESSION[$username]))
{
return false;
}
$id = $_SESSION[$roleid];
if((time()- $_SESSION["created"]) >= 3600)
{
session_destroy();
return false;
}
return $id;
}
and check it in every page or use this in header page.
if(!($userid=sessionValidate($username)))
{
error_log("No session logging out ....");
header('Location: index.php');
}
UPDATE ::
Definition
session_status — Returns the current session status
Return Values
PHP_SESSION_DISABLED- if sessions are disabled.
PHP_SESSION_NONE - if sessions are enabled, but none exists.
PHP_SESSION_ACTIVE - if sessions are enabled, and one exists.

Related

PHP login form does not read user level

I want to make a login form which can be used by normal users and admins. The code should tell the difference between normal users and admins and based on it, start a new session after user is logged in (admin or user session). In my database table, I added "level" column which should determine if user is an admin or not (for ex.: if the user level is 3, then they are admin).
Here is my login.php file:
if (isset($_POST['submit'])) {
include_once 'database.php';
$username = $_POST['username'];
$password = $_POST['password'];
if (!$username or !$password) {
header('Location: login.php');
} else {
$execution = "SELECT level FROM users WHERE name = '$username' AND password = '$password';";
$result = mysqli_query($database, $execution);
if (mysqli_num_rows($result) == 1) {
session_start();
$_SESSION['user'] = $username;
header('Location: login.php');
exit();
} elseif (mysqli_num_rows($result) == 3) {
session_start();
$_SESSION['admin'] = $username;
header('Location: index.php');
exit();
} else {
header('Location: login.php');
exit();
}
}
}
The code does not work because when I try to log in with a user that has LEVEL 3 in database, it still starts the normal user session and does not go through the elseif statement that I wrote above. How do I fix this? Maybe I am doing this completely wrong and there is another way to do this admin/user login thing?
Btw: I do understand that I'm storing passwords in plain text here, but right now I am only experimenting with the code and do not plan to upload it to a website.
Because you aren’t checking the user’s level at all.
Your first if block only checks if the result has one row.
Also, you should use prepared statements to prevent injection.
This is the correct code:
if (isset($_POST['submit'])) {
include_once 'database.php';
$username = $_POST['username'];
$password = $_POST['password'];
if (!$username or !$password) {
header('Location: login.php');
} else {
$execution = mysqli_prepare($database, "SELECT level FROM users WHERE name = ? AND password = ?;";
mysqli_stmt_bind_param($execution, "ss", $username, $password);
mysqli_stmt_execute($execution);
$result = mysqli_stmt_get_result($execution);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
session_start();
if ($row['level'] == 1) {
$_SESSION['user'] = $username;
header('Location: login.php');
}
elseif ($row['level'] == 3) {
$_SESSION['admin'] = $username;
header('Location: index.php');
}
exit();
echo "$result";
} else {
header('Location: login.php');
exit();
}
}
}
Here is your code updated.
You need to get the value of level in order to apply the permissions.
session_start();
if ($result->num_rows > 0){
if($row['level'] == 1){
$_SESSION['user'] = $username;
header('Location: login.php');
exit();
}elseif( $row['level'] == 3){
$_SESSION['admin'] = $username;
header('Location: index.php');
exit();
}else{
header('Location: login.php');
exit();
}
}
Hope it helps.

PHP session page protect not functioning as thought

This is the login PHP code
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: index.php");
}
require 'database.php';
if(!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT id,user,password FROM users WHERE user = :user');
$records->bindParam(':user', $_POST['username']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if(count($results) > 0 && md5($_POST['password'], $results['password']) ){
$_SESSION['user_id'] = $results['id'];
header("Location: index.php");
} else {
$message = 'Sorry, something went wrong';
}
?>
This is what is supposed to protect my page
<?php
session_start();
if(!isset($_SESSION['user_id']) || $_SESSION['user_id']!=1){
header('Location: login.php');
}
?>
Even when I am logged in it redirects me to my login.php.
What am I missing?

PHP Session to restrict access to file

index.php
session_start();
if(isset($_POST['login'])){
$username = mysqli_real_escape_string($con,$_POST['username']);
$pass = mysqli_real_escape_string($con,$_POST['userpass']);
$sel_user = "select * from users where user_name='$username' AND user_password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;
header("location:display.php");
die();
}
else {
echo "<script>alert('Username or Password is not correct, please try again!')</script>";
}
}
display.php
session_start();
if(!$_SESSION['loggedIn']) {
header("location: index.php");
die();
}
Hello, I'm trying to figure out why my index.php is not letting me properly login and access my display.php The password and username is right, but keeps redirecting me to index.php Any ideas why?
Why don't you use Cookies instead?
In your login.php page instead of:
if($check_user>0) {
$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;
header("location:display.php");
die();
}
Do this:
if($check_user>0) {
$_SESSION['user_name']=$username;
$Month = 86400 + time();
setcookie('user', $username, $Month);
header("Location:display.php");
}
and then on your display.php
session_start();
if(!isset($_COOKIE['user']))
{
header("location:index.php");
die();
}

Logout script is not working

Please help with my logout script. I am sorry for dumb mistakes I am very new to php. Please provide me with details and examples of how to fix this. Thank you so much.
Login Page: There are 4 types of users. Each user will get a separate home page.
<?php
session_start();
require_once('common/config.php');
if(isset($_POST['username']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM `users` WHERE username='".$username."' and password='".$password."'";
$result = mysql_query($sql) or die(mysql_error());
$fetched = mysql_fetch_array($result);
if ($fetched['user_type'] == "admin")
{
header('location: adminhomepage.php');
}
else if ($fetched['user_type'] == "po")
{
header('location: pohomepage.php');
}
else if ($fetched['user_type'] == "pw")
{
header('location: pwhomepage.php');
}
else if ($fetched['user_type'] == "ps")
{
header('location: pshomepage.php');
}
else
{
header('location: invalid.php');
exit();
}
}
?>
Home Page: For instance this is the admin home page.
<?php
session_start();
if (isset($_SESSION['username']) && ($_SESSION['username'] !== 1))
{
header('Location: login.php');
}
?>
Logout Page
<?php
session_start();
$_SESSION['username'] =0;
?>
Logout Button
<form action = "logout.php">
<input id="logoutbutton" type="submit" value="Logout">
</form>
logout page
<?php
session_start();
unset($_SESSION['susername']);
$_SESSION['susername'] = "";
session_destroy();
header("location:index.php");
?>
login.php
session_start();
if (isset($_SESSION['uname']) == "")
{
require_once('index.php');
}
$user_name = $_POST['user_name'];
$user_pass = $_POST['user_pass'];
$_SESSION['susername'] = $user_name; // or other value
logout page -
<?php
session_start();
$_SESSION['username'] =0;
?>
you have to start the session first before accessing it.
In your logout.php please update this code...
<?php
session_start();
if(isset($_SESSION['username']))
{
unset($_SESSION['username']);
header('Location: login.php');
}
?>
use unset($_SESSION['susername']) or session_destroy
Edit:
With your new information, it's clear you never actually set the $_SESSION['username'] value.
if ($fetched['user_type'] == "admin")
{
$_SESSION['username'] = $username;
header('location: adminhomepage.php');
}
else if ($fetched['user_type'] == "po")
{
$_SESSION['username'] = $username;
header('location: pohomepage.php');
}
else if ($fetched['user_type'] == "pw")
{
$_SESSION['username'] = $username;
header('location: pwhomepage.php');
}
else if ($fetched['user_type'] == "ps")
{
$_SESSION['username'] = $username;
header('location: pshomepage.php');
}
else
{
header('location: invalid.php');
}
exit();
Your problem is your comparison.
if ($_SESSION['username'] != 1)
This is true if $_SESSION['username'] is not set, null, a string, false, etc...
This might be more what you are looking for.
if (isset($_SESSION['username']) && is_string($_SESSION['username']) && strlen($_SESSION['username']))
And you need to fix your SQL injection problem here
$sql = "SELECT * FROM `users` WHERE username='".$username."' and password='".$password."'";
Escape variables with mysql_real_escape_string or use PDO with proper prepared statements.
You should also store passwords as hashes with password_hash(). Fetch the user, compare stored hash to password with password_verify.
if (!password_verify($password, $fetched["password"])) {/* wrong password, show error or something */}

Login Not Working PHP MySQL

I'm trying to fix my login page...
It works fine on the login.php with redirecting but on the index it doesn't redirect even if the session is empty. Any pointers? I'm new to this, so forgive me if it's really obvious.
<?php
require_once('../includes/config.php');
session_start();
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='no'){
// not logged in
header("location: login.php");
exit();
} else {
$_SESSION['loggedin'] = 'yes';
}
?>
<?php
include("../includes/config.php");
$error = NULL;
$atmpt = 1;
if (!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='yes'){
// logged in
header("location: index.php");
exit();
}
if(isset($_POST['login']))
{
/* get username and password */
$username = $_POST["username"];
$password = $_POST["password"];
/* MySQL Injection prevention */
$username = mysqli_real_escape_string($mysqli, stripslashes($username));
$password = mysqli_real_escape_string($mysqli, stripslashes($password));
/* check for user in database */
$query = "SELECT * FROM admin_accounts WHERE username = '$username' AND password = '$password'"; // replace "users" with your table name
$result = mysqli_query($mysqli, $query);
$count = $result->num_rows;
if($count > 0){
//successfully logged in
$_SESSION['username']=$username;
$_SESSION['loggedin']='yes';
$error .= "<div class='alert alert-success'>Thanks for logging in! Redirecting you..</div>";
header("refresh:1;url=index.php");
} else {
// Login Failed
$error .= "<div class='alert alert-danger'>Wrong username or password..</div>";
$_SESSION['loggedin']='no';
$atmpt = 2;
}
}
?>
The line
session_start();
should be the very first line in the php script.
Just modify first three lines.
As session_start() should be put before any output has been put on the browser (even space).
<?php
session_start();
require_once('../includes/config.php');
if (empty($_SESSION['loggedin']) && $_SESSION['loggedin']=='no') {
...

Categories