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.
Related
I am trying to login with GET method in PHP.
I tried:
login.php
<?php
session_start();
require_once 'class.user.php';
$user_login = new USER();
if($user_login->is_logged_in()!="")
{
$user_login->redirect($web.$_SESSION['user_name']);
}
if(isset($_GET['user']) && isset($_GET['password']))
{
$uname = trim($_GET['user']);
$upass = trim($_GET['password']);
if($user_login->login($uname,$upass))
{
$user_login->redirect($uname);
}
}
?>
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['userAccess']=="Y")
{
if($userRow['userPass']==md5($upass))
{
$_SESSION['userSession'] = $userRow['userID'];
$_SESSION['loggedin_time'] = time();
$_SESSION['user_name'] = $userRow['userName'];
return true;
}
else
{
header("Location: signin.php?error");
exit;
}
}
else
{
header("Location: default.php");
exit;
}
}
else
{
header("Location: inactive.php");
exit;
}
}
else
{
header("Location: signin.php?error");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
I am always getting error showing that: wrong details
I cross checked the user name & password with MySQL. They are correct!
This is because you are encrypting your encrypted password, which results in wrong details
Change if($userRow['userPass']==md5($upass)) to if($userRow['userPass']==($upass))
Hope this will resolve your error.
so I have a login page named index.php, the page does not seem to redirect to the home.php page.
I have tried to log in using all the correct user details but it stills stays on the index.php page and it also clears the data in the fields
I looked through my code and I cant seem to find the problem
<?php
require_once'Dbconfig.php';
function login($umail, $upass)
{
$stmt = $dbh->prepare("SELECT * FROM users WHERE
emailAddress=:umail AND userPass=:upass");
$stmt->execute(array(':umail'=>$umail, ':upass'=>$upass));
$userRow=$stmt->fetch(PDO::FECTH_ASSOC);
if($stmt->rowCount() ==1)
{
$hashed = $this->get_user_hash($upass);
if($this->password_verify($upass, $hashed) == 1)
{
$_SESSION['user_session'] =
$userRow['emailAddress'];
return true;
}
else
{
return false;
}
}
}
if(isset($_POST['btn_login']))
{
$umail = $_POST['txt_umail'];
$upass = $_POST['txt_upass'];
if($user->login($umail, $upass))
{
header('Location: home.php');
exit;
}
else
{
$error[] = 'Wrong email or password!';
}
}
?>
You can try using else condition
<?php
require_once'Dbconfig.php';
function login($umail, $upass){
$stmt = $dbh->prepare("SELECT * FROM users WHERE emailAddress=:umail");
$stmt->bindValue(":umail", $umail);
$stmt->execute();
$userRow = $stmt->fetchAll();
if($stmt->num_rows ==1){
$hashed = $this->get_user_hash($upass);
if($this->password_verify($upass, $hashed)){
$_SESSION['user_session'] = $userRow['emailAddress'];
return true;
}else{
return false;
}
}
}
?>
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;
}
}
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();
?>
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?