Session is not being stored - php

Would anyone please show me how to solve this problem? I spent many days looking for the solution, but I couldn't find one.
Here's my problem.
"login.php" file:
require_once("./include/membersite_config.php");
if(isset ($_POST['submitted']))
{
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("login-home.php");
}
}
**membersite_config . php ** contains host, username, pass, and also calls **fg_membersite . php ** which contains functions:
function Login()
{
if(empty($_POST['username']))
{
$this->HandleError("UserName is empty!");
return false;
}
if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if(!isset($_SESSION))
{
$sessid = session_start();
}
if(!$this->CheckLoginInDB($username, $password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $username;
** echo empty($_SESSION[$sessionvar])? 'true' : 'false'; **
return true;
}
function CheckLogin()
{
if(!isset($_SESSION))
{
session_start();
}
$sessionvar = $this->GetLoginSessionVar();
** echo empty($_SESSION[$sessionvar])? 'true' : 'false'; **
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
function GetLoginSessionVar()
{
$retvar = $this->rand_key;
$retvar = 'usr_' . substr($retvar, 0);
return $retvar;
}
function CheckLoginInDB($username, $password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$username = $this->SanitizeForSQL($username);
$pwdmd5 = $password;
$qry = "Select name, email from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";
$result = mysql_query($qry, $this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error logging in. The username or password does not match");
return false;
}
$row = mysql_fetch_assoc($result);
$_SESSION['name_of_user'] = $row['name'];
$_SESSION['email_of_user'] = $row['email'];
return true;
}
**login - home . php ** after successfully logged in:
require_once("./include/membersite_config.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
Th problem is: I already echoed to check the status of the $_SESSION[] array. After I input the correct username and password, the echo empty($_SESSION[$sessionvar]) ? 'true': 'false'; in Login function shows false, but the one in CheckLogin shows true. I dont know why.

session_start() starts or continues the session by adding cookies or a query parameter to identify the user. You have to place it at the very top of your template (before anything is printed out, even a blank line), even if the user already has a session:
<?php
session_start();
?>

Related

I can't get userid from session?

some help if you wish please for beginner user
will you please show me where is my code problem ?
i want to get user id from $_SESSION['userid']
but it's not working
i success to get username but not the id
i include session_start(); on each page to want to use it
but it's not showing the user id
only username working
here are my code
<?php
include("conn.php");
// variable declaration
$userid = "";
$username = "";
$email = "";
$errors = array();
$_SESSION['success'] = "";
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
unset($_SESSION['username']);
unset($_SESSION['userid']);
unset($_SESSION['user_type']);
header("location: ../login.php");
}
// return user array from their id
function getUserById($id){
global $conn;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// LOGIN USER
function login(){
global $conn, $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 = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1) { // user found
// Storing username in session variable
session_start();
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
$userid=$row['id'];
$username=$row['username'];
$user_type=$row['user_type'];
$_SESSION['username'] = $username;
$_SESSION['userid'] = $userid; // <-this variable should now exist
$_SESSION['user_type'] = $user_type;
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{
if ($logged_in_user['user_type'] == 'superuser') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: superuser/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 isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
function isSuperuser()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'superuser' ) {
return true;
}else{
return false;
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
// escape string
function e($val){
global $conn;
return mysqli_real_escape_string($conn, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
?>
As far as i can tell, your script would run.
Though please note that when using with sessions and $_SESSION globals, you have to initialise it first by adding session_start(); at the top of your page.
You should also dig into using PDO rather than mysqli or mysql.
I know this looks complicated, but it's the safest way to handle database queries.
Also don't use md5, use password_hash();
I also recommend adding var_dump($row); in this if statement, to see what data you are working with:
if (mysqli_num_rows($results) == 1) { // user found

Logged session goes to all url

I have two users me & bai.
If me logins it goes to http://localhost/Ebooks/new/me
And if bai logins it goes to http://localhost/Ebooks/new/bai
I am using sessions so that no one goes their respective links without login.
But I am facing the problem that if bai is logged in, and the user types http://localhost/Ebooks/new/me in the URL bar, it goes to that folder, but it should not as logged in user is another.
The code goes here:-
http://localhost/Ebooks/new/index.php
<?php
session_start();
require_once 'class.user.php';
$user_login = new USER();
if($user_login->is_logged_in()!="")
{
$user_login->redirect($logout);
}
if(isset($_POST['btn-login']))
{
$uname = trim($_POST['txtuname']);
$upass = trim($_POST['txtupass']);
if($user_login->login($uname,$upass))
{
$user_login->redirect($uname);
}
}
?>
http://localhost/Ebooks/new/class.user.php
public function login($uname,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_users WHERE userName=:username");
$stmt->execute(array(":username"=>$uname));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['userPass']==md5($upass))
{
$_SESSION['userSession'] = $userRow['userID'];
return true;
}
else
{
header("Location: index.php?error");
exit;
}
}
else
{
header("Location: index.php?inactive");
exit;
}
}
else
{
header("Location: index.php?error");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
$_SESSION['userSession'] = false;
}
http://localhost/Ebooks/new/bai/index.php & http://localhost/Ebooks/new/me.php both have :-
<?php require_once '../home.php' ?>
http://localhost/Ebooks/new/home.php
<?php
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect($web);
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Please help me, how to clear it out!
Here is solution:
store username also in session. So in login
$_SESSION['userSession'] = $userRow['userID'];
$_SESSION['user_name'] = $userRow['userName'];
Then in home.php check username with path
if($_SERVER['REQUEST_URI'] != $_SESSION['user_name'])
{
//show error or redirect to user page
}
else
{
//continue your code
}
EDIT try edited code for url checking (in home.php)
$url = $_SERVER['REQUEST_URI'];
$exp = explode("/",$url);
$match_name= "";
if(isset($exp[count($exp)-2]) && $exp[count($exp)-2] != "")
{
$match_name= $exp[count($exp)-2];
}
elseif(isset($exp[count($exp)-1]) && $exp[count($exp)-1] != "")
{
$match_name= $exp[count($exp)-1];
}
if($match_name != $_SESSION['user_name'])
{
//show error or redirect to user page
}
else
{
//continue your code
}
Very simple, compare the requested directory with the user's username and see if they match, if they do, show it, other wise show them an error message.
<?php
$exists = strrpos($url, '/');
$requested_username = $exists === false ? false : substr($url, $exists + 1);
if ($requested_username == $_SESSION['username_here']) {
/** Pass... **/
} else {
/** Fail... **/
}
?>
You'd replace $url with the requested URL.
Live Example
Repl
You need to check the session on "me" page, if user is authorised then go on otherwise redirect him to "bai" page. And same to other type user.

Make function to check login status with session in PHP

i want to make toefl test. so there will be a login button. when someone login in, then the login button will be logout button. but when i login in, the login button was not changed. please help me
function to check login status (i save this function in lib_function.php):
<?php session_start(); ?>
<?php
function check_login(){
$hasil = 0;
if (isset($_SESSION['email'])) {
$mail = $_SESSION['email'];
}
if (isset($_SESSION['pass'])) {
$pass = $_SESSION['pass'];
}
if (!empty($mail) and !empty($pass)){
$hasil = 1;
}
return $hasil;
}
?>
index.php:
<?php session_start();
require_once("connection.php");
?>
<?php include("lib_function.php"); ?>
<--header-->
<?php
$check = check_login();
if ($check == 1){
echo "Login <strong class=\"hover\">";
}else{
echo "Logout <strong class=\"hover\">";
}
?>
this is my login process:
<?php
session_start();
require_once("connection.php");
$email = $_POST['email'];
$password = $_POST['password'];
$cekuser = mysql_query("SELECT * FROM user WHERE email = '$email'");
$jumlah = mysql_num_rows($cekuser);
$hasil = mysql_fetch_array($cekuser);
if($jumlah == 0) {
echo "<script>alert('Email has registered!'); window.location = 'index.php'</script>";
} else {
if($pass > $hasil['password']) {
echo "<script>alert('Wrong password!'); window.location = 'index.php'</script>";
} else {
$_SESSION['email'] = $hasil['email'];
header('location:index.php');
}
}
?>
You check if $_SESSION['pass'] is set in your check_login function, but you never set it during the login process.
Either set $_SESSION['pass'] or remove and !empty($pass) from check_login().
Always try to check if the Session is already active before starting one. You also might want to assign default values of say NULL to the $mail & $pass variables inside your check_login() function because at a point, you were checking if $mail and $pass were empty. What if they were not even set at all? In this case those variables would not have existed at all...
<?php
// FILE:: lib_function.php
function check_login(){
$hasil = 0;
// GET THE $mail & $pass FROM SESSION; ASSIGNING A DEFAULT NULL
// TO EACH OF THEM IF THEY ARE NOT YET SET...
$mail = isset($_SESSION['email']) ? $_SESSION['email'] : null;
$pass = isset($_SESSION['pass']) ? $_SESSION['pass'] : null;
if (!empty($mail) and !empty($pass)){
$hasil = 1;
}
return $hasil;
}
// FILE:: index.php
// START SESSION ONLY IF IT IS NOT ALREADY ACTIVE:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
require_once("connection.php");
include("lib_function.php");
// HEADER HERE
$check = check_login();
if ($check == 1){
echo "Login <strong class=\"hover\">";
}else{
echo "Logout <strong class=\"hover\">";
}
?>
try this:
function login($email) {
$_SESSION['email'] = $email;
}
function is_logged() {
return isset($_SESSION['email']);
}
function logout() {
session_destroy();
}

PHP Error in validating SESSION variable

So I've made a login system here, it initiates a session, checks if the password is correct and then sets the session variables.
Here are a few things you might want to note:
It successfully logs in
There is no problem with the mysql connection
All files are places correctly in folders
There are no warnings or error messages
The MYSQL Table structure is correct and there are no errors in database
Note: all functions I'm about to define are in the same file 'functions.php'
Over here we have the session function
include_once("global_config.php");
include_once("db_connect.php");
function sec_session_start()
{
$session_name = 'sec_session_id';
$secure = SECURE;
$httponly = true;
if(ini_set('session.use_only_cookies', 1) === FALSE)
{
echo "Could not initiate a secure session";
exit;
}
$cookieparams = session_get_cookie_params();
session_set_cookie_params($cookieparams['lifetime'],$cookieparams['path'],$cookieparams['domain'],$secure,$httponly);
session_name($session_name);
session_start();
session_regenerate_id();
}
The global_config file define the mysql password, database, user and host and the db_connect file simply return the mysqli_connect to connect to the database.
And this over here is the login function
function login($user,$pass){
sec_session_start();
$link=linkit();
if(empty($user) || empty($pass) || !isset($user) || !isset($pass)){
echo "Error Code: 313, Please contact network administrator for more information";
exit;
}else{
$usercheck = "SELECT `id`,`username`,`password`,`salt` FROM `".LOGINTABLE."` WHERE `username`=? LIMIT 1";
if($stmt=$link->prepare($usercheck)){
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$username,$realpassword,$salt);
$stmt->fetch();
$stmt->close();
if(empty($realpassword)){
echo 'Unrecognized Username, Please enter a valid username';
exit;
}else{
if($realpassword===$pass){
$_SESSION['username'] = $user;
$_SESSION['user_id'] = $id;
$_SESSION['login_string'] = hash('sha512',$pass);
return true;
}else{
echo "Invalid Password!";
exit;
}
}
}
}
}
The linkit() method is the one defined in db_connect.php which returns mysqli_connect. Also note that the script successfully makes it to setting the Session variable which means that it does return true.
NOW THE PROBLEM is this, when I'm checking for logged in status
function check_login()
{
if(isset($_SESSION['user_id']) &&
isset($_SESSION['login_string']) && isset($_SESSION['username']))
{
$user_id = $_SESSION['user_id'];
$username = $_SESSIOOO['username'];
$login_string = $_SESSION['login_string'];
$pwd_check = "SELECT `password` FROM `".LOGINTABLE."` WHERE `user_id`=? LIMIT 1";
if($stmt = linkit()->prepare($pwd_check))
{
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->bind_result($realpassword);
$stmt->fetch();
$stmt->close();
$hashedpass = hash('sha512',$realpassword);
if($login_string==$hashedpass){
return true;
}else{
return false;
}
}else{
return true;
}
}else{
return false;
}
}
AND FINALLY, this is WHERE I process my login script. Also note that there are no errors in POST methods or anything else. They all work fine.
This is in a separate php file and NOT in the functions.php
<?php
include_once '../includes/functions.php';
if(empty($_POST['loginuser']) || !isset($_POST['loginuser']) || !isset($_POST['id']) || empty($_POST['id']) || !isset($_POST['password']) || empty($_POST['password']))
{
echo "Error Code: 412, Please contact network administrator for more information";
exit;
}else{
if($_POST['loginuser']==="true")
{
$user = $_POST['id'];
$pass = $_POST['password'];
if(login($user,$pass)==true)
{
echo "Logged In!";
}else
{
echo "Failed to login, check your username or password";
}
}
}
?>
Additional Information :
The response I get is "Logged In"
Session is successfully creaated
PROBLEM: When I check for the login status, it returns false despite of having the session variables set.
In check_login you are hashing the password and then compare the unhashed password
function check_login()
{
if(isset($_SESSION['user_id']) &&
isset($_SESSION['login_string']) && isset($_SESSION['username']))
{
$user_id = $_SESSION['user_id'];
$username = $_SESSIOOO['username'];
$login_string = $_SESSION['login_string'];
$pwd_check = "SELECT `password` FROM `".LOGINTABLE."` WHERE `user_id`=? LIMIT 1";
if($stmt = linkit()->prepare($pwd_check))
{
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->bind_result($realpassword);
$stmt->fetch();
$stmt->close();
$hashedpass = hash('sha512',$realpassword);
if($login_string==$hashedpass ){
return true;
}else{
return false;
}
}else{
return true;
}
}else{
return false;
}
}

PHP session problems

I have a login page and a 'member's area' page, the login code is here:
login.php
if ($account->is_logged_in())
{
$route->to(ACCOUNT_URL);
}
elseif (isset($_POST['username']))
{
if ($account->authenticates())
{
if ($account->log_in()) $route->to(ACCOUNT_URL);
}
else
{
$flash->set('error', 'The credentials you provided are incorrect.');
}
}
the functions (in a different file)
public function log_in ()
{
session_unset();
session_destroy();
if(session_start())
{
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $_POST['username'];
}
}
public function authenticates ()
{
$username = $_POST['username'];
$password = $_POST['password'];
if (ctype_alnum($username) && ctype_alnum($password))
{
$username = mysql_real_escape_string(filter_var($username, FILTER_SANITIZE_STRING));
$password = $this->encrypt(mysql_real_escape_string(filter_var($password, FILTER_SANITIZE_STRING)));
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Then my members area page:
if ($account->is_logged_in())
{
echo 'logged in';
}
elseif (!$account->is_logged_in())
{
echo 'not logged in';
echo session_id();
print_r($_SESSION['logged_in']);
}
login.php redirects me (meaning it authenticates my account), but when I get to members.php it echoes out 'not logged in' and that is all.
You'll need to call session_start() at the top of members.php (and any page that needs to access the $_SESSION.
// Must initiate the session to test if logged in.
session_start();
if ($account->is_logged_in())
{
echo 'logged in';
}
elseif (!$account->is_logged_in())
{
echo 'not logged in';
echo session_id();
print_r($_SESSION['logged_in']);
}
Do you have session_start() at the very beginning of all scripts which use sessions?

Categories