PHP session problems - php

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?

Related

direct user access of pages through url

hi i want to block direct URL access to my pages using below php codes but if I include it to my forms I can't login even after typing my username and password it's like I'm locked out of my application. can someone help please
that's my security.php file
<?php
if(!isset ($_SESSION['user']))
{
header ('location:user_login.php');
}
?>
and the user login file
<?php
if (isset($_POST['btnLogin']))
{
$user = $_POST['user'];
$password = $_POST['password'];
//sql injection security
$user = mysqli_real_escape_string($con,$user);
$password = mysqli_real_escape_string($con,$password);
//select database
$db = mysqli_select_db($con,'nesthet');
$query = "SELECT * from users where user='$user' AND password='$password'";
$query_run = mysqli_query($con,$query);
$role = mysqli_fetch_array($query_run);
//user redirection base on user role
if($role['role'] == "admin"){
session_start();
$_SESSION['user'] = $user;
header('location: admin.php');
}
else if($role['role'] == "user") {
$_SESSION['user'] = $user;
header('location: mdi_parent.php');
}
else {
$_SESSION['status'] = "Username or password is invalid";
header('location: index.php');
}
}
?>
In security.php you should execute session_start() before using $_SESSION variable
<?php
if(!isset ($_SESSION['user']))
{
header ('location:user_login.php');
}
?>
In your code, you just only start session when role is admin
if($role['role'] == "admin"){
session_start();
$_SESSION['user'] = $user;
header('location: admin.php');
}
else if($role['role'] == "user") {
$_SESSION['user'] = $user;
header('location: mdi_parent.php');
}
else {
$_SESSION['status'] = "Username or password is invalid";
header('location: index.php');
}

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.

Session is not being stored

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();
?>

Get user's ID from mysql UPON login and echo to screen php/mysql

login/index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
<?php
if($_SESSION['valid'] == 1){ #user has logged in by creating a session var
echo "<a href='logout.php'>Logout</a>";
}
else{
return false;
}
?>
Once login/index.php is filled out, it validates a valid login with check_buyer.php:
<?php
session_start(); #recall session from index.php where user logged
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return true;
}
function validateUser() {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = (isset($ifUserExists['uID'])) ? $ifUserExists['uID'] : null;
$_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
If a valid user is provided, it redirects to buyer/index.php which includes the buyer_profile.php page (farther below):
<?php
session_start();
if($_SESSION['uUserType'] != 1) // error
{
die("
<div class='container_infinity'>
<div class='container_full' style='position:static;'>
<img src='img/error/noAccess.png' style='float:left;' /> <br />
<h2>403 Error: You may not view this page. Access denied.</h2>
</div>
</div>
");
}
function isLoggedIn()
{
return ($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: ../index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
echo 'buyerid: '.$_SESSION['uID'];
require_once('buyer_profile.php');
}
else{
echo "<a href='../index.php'>Login</a>";
}
?>
buyer_profile.php
Which is basic HTML with the session_start(); at the first line
The problem lies in login/buyer/index.php, where echo 'buyerid: '.$_SESSION['uID']; does not display anything. It should be outputting the uID of the user logged in from the SELECT query in the login/check_buyer.php why isn't it storing this value upon logging in??
Anyone??
Perhaps the SELECT query is returning false so $ifUserExists is not having any value set to it (other than false).
You can test this by using print_r($ifUserExists);, which will print out the array if it is a set and valid array; otherwise, it will not print anything.
You can also try this code, that I think might solve the problem.
list($ifUserExists) = ($result) ? #array_values(mysqli_fetch_assoc($result)) : NULL;
$_SESSION["uID"] = ($ifUserExists && $ifUserExists["uId"]) ? $ifUserExists["uId"] : NULL;
# insert your couple other lines of code here, I will not write them to save space
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
elseif ($_SESSION["uID"]) {
validateUser();
}
else {die("error!");}

Categories