On my website, there is a function for logging in and logging out. Upon login, I set the session variables pass (which is hashed password), uid which is the ID of the user logged in and loggedIn (boolean):
$hashedpass = **hashed pass**;
$_SESSION['pass'] = $hashedpass or die("Fel 2");
$_SESSION['uid'] = $uid or die("Fel 3");
$_SESSION['loggedIn'] = true or die("Fel 4");
header("Location:indexloggedin.php");
On every page, I check if the visitor is logged in by
Checking the status of $_SESSION['loggedIn'],
Searching the database for the user with the ID $_SESSION['uid'],
Checking if the hashed password in the database matches the hashed password in the session variable:
$sespass = $_SESSION['pass'];
$sesid = $_SESSION['uid'];
$sql2 = "SELECT * FROM `users` WHERE `id` = '$sesid'";
$result2 = mysqli_query($db_conx, $sql2);
$numrows2 = mysqli_num_rows($result2);
if ($numrows2 != 1) {
$userOk = false;
}
while ($row = mysqli_fetch_array($result2,MYSQLI_ASSOC)) {
$dbpass = $row['pass'];
}
if ($sespass != $dbpass) {
$userOk = false;
} else {
$userOk = true;
}
My problem is that this seems to be working on some pages, while it doesn't work at others. For example, when I log in, I am instantly logged in to the homepage, but not to the profile page. However, after a few reloads, I am logged in to the profile page as well. The same thing happens when logging out.
For testing purposes, I tried to var_dump the password variables as well as the userOk status on the index page, and this is where I noticed something interesting. When I log out, the password variables are set to be empty, and $userOk is false, according to what that is shown at index.php?msg=loggedout. But when I remove the ?msg=loggedout (and only leave index.php), the password variables are back to their previous value, and I am no longer logged out... After a few reloads, I am once again logged out.
Why is my session variables not working as expected? It feels like as if it takes time for them to update, which is very weird. I have tried with caching disabled (both through headers and through the Cache setting in my browser).
Just tell me if you need more info.
You have initialization session_start() on every Site?
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
After contacting my hosting provider, it was actually a hosting issue. It is now resolved!
Thanks,
Jacob
Related
On login I'm creating the following cookies based on a Remember Me checkbox:
$_SESSION['username'] = $username;
//creates a cookie if Remember Me is checked
if(isset($_POST['remember'])){
$expire_time = time()+86400;
setcookie("lion123_rmbr", $email, $expire_time);
setcookie("lion123_rmbr_usrnm", $username, $expire_time);
}
Just above I have the session being created on just the login.
The idea of course is to be able to close the browser, re-open and be able to access the members area without having to login. In header.php I have the following recall:
if (isset($_SESSION['username']) || isset($_COOKIE['lion123_rmbr']) || isset($_COOKIE['lion123_rmbr_usrnm'])) {
$userLoggedIn = $_SESSION['username'];
$user_details_query = mysqli_query($con, "SELECT * FROM users WHERE username='$userLoggedIn'");
$user = mysqli_fetch_array($user_details_query);
}
else{
header("Location: register.php");
}
When I open and close the browser, then navigate to members area, the cookies allow for me to do this; however, the user specific data is missing because $_SESSION['username'] = $username; is not being set on login & of course being terminated once the browser is closed. So I'm getting the error that username is not defined.
I thought that adding the second cookie for username might be the fix...nope :) Any help on how to activate a user session would be appreciated - if the only way the session is created is through login, how can this data be passed to activate $userLoggedIn?
Thankyou.
This code below is having a problem..
<?php
session_start();
include_once("databaseConnect.php"); // This creates $database by mysqli_connect().
if(isset($_SESSION['id'])){ // checking if user has logged in
$id = $_SESSION['id'];
$sql = "SELECT * FROM tableName WHERE id = '$id'";
$query = mysqli_query($database, $sql);
$row = mysqli_fetch_row($query);
$activated = $row[1]; // This is where I store permission for the user
if(!($activated == 2 || $activated == 3)){ // if the user has not enough permission:
header("Location: http://myWebsiteIndex.php");
}
// code for users
}else{
header("Location: http://myWebsiteIndex.php");
}
?>
I have a user who has 3 for $activated, so they should be able to access.
When a user logges in to my website, it sets $_SESSION['id'] to store the id of the user.
This session variable is used to check if the user is logged in.
However, when I run the code several time, sometimes it works and sometimes it doesn't. Sometimes, it will run the '// code for users' part, and sometimes it will just redirect to my 'http://myWebsiteIndex.php'.
How would I fix this??
First, try changing the headers to different redirects. What part of the conditional is failing? If the $_SESSION['id'] is not properly set it will redirect to the same url as it will redirect to when the user does not have proper permissions. Changing one of them will show you what part is executed when you encounter the behaviour.
Second, the comment from Barth is helpful. The if(!($activated == 2 || $activated == 2)) evaluation seems incorrect. You are evalutaing for (not) 2 or 2.
Third, take note of your session data and compare when the redirect happens to when it does not.
First of all, I am testing on localhost. I have this index.php file which contains the following "remember me" checkbox:
<input type="checkbox" id="login_remember" name="login_remember">
The login form posts to loginvalidate.php, which includes the following php script. I have included a lot of comments to ease the process of reading my code. Note that I'm pretty sure that everything below works fine.
if (isset($_POST['login_submit'])) { //SETS VARIABLES FROM FORM
$email = $_POST[trim('login_email')];
$password = $_POST['login_password'];
$remember = isset($_POST['login_remember']) ? '1' : '0';
$db_found = mysqli_select_db($db_handle,$sql_database); //OPENING TABLE
$query = "SELECT password FROM registeredusers WHERE email = '$email'";
$result = mysqli_query($db_handle, $query) or die (mysqli_error($db_handle));
$row = mysqli_fetch_assoc($result);
$numrows = mysqli_num_rows($result);
if ($numrows!=0) //IF EMAIL IS REGISTERED
{
if ($row['password'] == $password) { //IF PASSWORD IN DATABASE == PASSWORD INPUT FROM FORM
if ($remember == '1'){ //IF USER WANTS TO BE REMEMBERED
$randomNumber = rand(99,999999); //RANDOM NUMBER TO SERVE AS A KEY
$token = dechex(($randomNumber*$randomNumber)); //CONVERT NUMBER TO HEXADECIMAL FORM
$key = sha1($token . $randomNumber);
$timeNow = time()*60*60*24*365*30; //STOCKS 30 YEARS IN THE VAR
$sql_database = "registeredusers";
$sql_table = "rememberme";
$db_found = mysqli_select_db($db_handle,$sql_database); //OPENING TABLE
$query_remember = "SELECT email FROM rememberme WHERE email = '$email'"; //IS THE USER IN TABLE ALREADY
$result = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));
if (mysqli_num_rows($result) > 0) { //IF USER IS ALREADY IN THE REMEMBERME TABLE
$query_update = "UPDATE rememberme SET
email = '$email'
user_token = '$token'
token_salt = '$randomNumber'
time = '$timeNow'";
}
else { //OTHERWISE, INSERT USER IN REMEMBERME TABLE
$query_insert = "INSERT INTO rememberme
VALUES( '$email', '$token', '$randomNumber', '$timeNow' )";
}
setcookie("rememberme", $email . "," . $key, $timenow);
}
header('Location: homepage.php'); //REDIRECTS: SUCCESSFUL LOGIN
exit();
}
Then, when I close the internet browser and come back to index.php, I want the cookie to automatically connect the user. This is in my index.php:
include 'db_connect.php';
$sql_database = "registeredusers";
$db_found = mysqli_select_db($db_handle,$sql_database); //OPENING TABLE
session_start();
if (isset($_COOKIE['rememberme'])) {
$rememberme = explode(",", $_COOKIE["rememberme"]);
$cookie_email = $rememberme[0];
$cookie_key = $rememberme[1];
$query_remember = "SELECT * FROM rememberme WHERE email = '$cookie_email'"; //IS THE USER IN TABLE ALREADY
$result_remember = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));
$row = mysqli_fetch_assoc($result_remember);
$token = $row['user_token'];
$randomNumber = $row['token_salt'];
$key = sha1($token . $randomNumber); //ENCRYPT TOKEN USING SHA1 AND THE RANDOMNUMBER AS SALT
if ($key == $cookie_key){
echo "lol";
}
}
The problem is, it never echoes "lol". Also, does anyone have any insight on how I could connect the users? AKA, what should go inside these lines:
if ($key == $cookie_key){
echo "lol";
}
Thank you! I'm still new to PHP and SQL so please bear with me if I have made some beginner errors.
EDIT!: After looking again and again at my code, I think that my error might lie in these lines. I'm not sure about the syntax, and the method I am using to store values into $token and $randomNumber:
$query_remember = "SELECT * FROM rememberme WHERE email = '$cookie_email'"; //IS THE USER IN TABLE ALREADY
$result_remember = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));
$row = mysqli_fetch_assoc($result_remember);
$token = $row['user_token'];
$randomNumber = $row['token_salt'];
A login script in PHP can be implemented using sessions.
Using Sessions
Making it simple, sessions are unique and lives as long as the page is open (or until it timeouts). If your browser is closed, the same happens to the session.
How to use it?
They are pretty simple to implement. First, make sure you start sessions at the beginning of each page:
<?php session_start(); ?>
Note: It's important that this call comes before of any page output, or it will result in an "headers already sent" error.
Alright, now your session is up and running. What to do next? It's quite simple: user sends it's login/password through login form, and you validate it. If the login is valid, store it to the session:
if($validLoginCredentials){
$_SESSION['user_id'] = $id;
$_SESSION['user_login'] = $login;
$_SESSION['user_name'] = $name;
}
or as an array (which I prefer):
if($validLoginCredentials){
$_SESSION['user'] = array(
'name' => $name,
'login' => 'login',
'whichever_more' => $informationYouNeedToStore
);
}
Ok, now your user is logged in. So how can you know/check that? Just check if the session of an user exists.
if(isset($_SESSION['user_id'])){ // OR isset($_SESSION['user']), if array
// Logged In
}else{
// Not logged in :(
}
Of course you could go further, and besides of checking if the session exists, search for the session-stored user ID in the database to validate the user. It all depends on the how much security you need.
In the simplest application, there will never exist a $_SESSION['user'] unless you set it manually in the login action. So, simply checking for it's existence tells you whether the user is logged in or not.
Loggin out: just destroy it. You could use
session_destroy();
But keep in mind that this will destroy all sessions you have set up for that user. If you also used $_SESSION['foo'] and $_SESSION['bar'], those will be gone as well. In this case, just unset the specific session:
unset($_SESSION['user']);
And done! User is not logged in anymore! :)
Well, that's it. To remind you again, these are very simple login methods examples. You'll need to study a bit more and improve your code with some more layers of security checks depending on the security requirements of your application.
reason behind your code is not working is
setcookie("rememberme", $email . "," . $key, $timenow); // this is getting expire exactly at same time when it is set
replace it with
setcookie("rememberme", $email . "," . $key, time() * 3600);//expire after 1hour
time()*60*60*24*365*30
this time is greater than 9999 year also you didn't need to set this horror cookie time.
that cookie time you were set is greater than 9999 years and php not allow for this configure.
in my opinion the best solution is setup new expire cookie time lower than 9999 :))
Does someone know why this cookie doesn't wanna work, I been trying a lot of different things but it doesn't wanna make a cookie at all.
Script I'am using:
$sql = mysql_query("SELECT id FROM plattegrond_gebruikers WHERE email = '$username' AND password = '$password' LIMIT 1")or die(mysql_error());;
if(mysql_num_rows($sql) > 0){
$row = mysql_fetch_assoc($sql);
// User found, now let's create the cookies for the user!
if(!$_COOKIE["userid"]) {
setcookie("userid",$row["id"],time()+3600,'/','nieuws.holapress.com');
if(isset($_COOKIE['userid'])){
$cookieSet = 'The cookie is ' . $_COOKIE['userid'];
} else {
$cookieSet = 'No cookie has been set';
}
echo $cookieSet;
}else{
echo"cookie excists";
}
return true;
} else {
return false;
}
Everything works like it should, it makes the query, it gets the users information but it just doesn't set a cookie, and after login I get the "No cookie has been set". does anyone know what I'm doing wrong?
Probably you checking on local machine with parameter nieuws.holapress.com. Change it to your localhost.
The cookie can be read after reloading the page, because the first time you set the cookie, it will be send to browser, the browser will save it, then, for next requests, the browser include the cookie, and the server can read it.
You need to put in 1 line: session_start(); In all pages
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
$goHere = 'Location: /index2.php?id=' . $id;
header($goHere);
exit;
}
I have the following code that once logged in, it $_GET the id and prepends to the url like index2.php?id=5 . How do I keep this id=5 in the URL no matter WHAT link they click on??
This id is grabbed from this:
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
What I want to do
Well way i have it setup, you login, it then sends you to the homepage such as index2.php?id=[someint] , if you click another link say 'prof.php', it removes the id=[someint] part, I want to keep it there in the url, so as long as a user is LOGGED in -- using my code above, the url might read: index.php?id=5, then go to another page it might read prof.php?id=5, etc, etc. This integer would obviously be dynamic depending on WHO logged in
Instead of passing around an ID in the URL, consider referring to the id value in the $_SESSION variable. That way the user can't modify the URL and see data they aren't supposed to see (or much worse), and you don't have to worry over appending it to every URL and reading it into a value every time you go to process a script. When the user logs in, you determine their ID - read it from a database, determine it realtime, whatever. Then store it in the $_SESSION and refer to it as needed. You can even use this as part of a check to see if the user is logged in - if they have no $_SESSION['id'] value, something is wrong and you make them log in.
The query string isn't the place for that, for a whole host of reasons. The most obvious one is that I can log in with a valid account, then change the number in the URL and it'll think I'm someone else.
Instead, just continue using the session as it's the proper way.
If you REALLY want to do it, you'd probably want to write a custom function for generating links
function makeLink ($link, $queryString = '')
{
return $link . '?id=' . (int) $_SESSION['id'] . ((strpos($queryString, '?') === 0) ? substr($queryString, 1) : $queryString);
}
called like
Click me
As a basic auth example using the ID...
<?php
// Session start and so on here
if (!isset($_SESSION['id']))
{
// Not logged in
header('Location: /login.php');
exit;
}
http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/ is a pretty straightforward full example of it.