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.
Related
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
This question already has answers here:
Variable errors in session for admin pages
(2 answers)
Closed 7 years ago.
Login script which I know needs some security which I will do once it works, I can log in until I add session info to top of admin pages then either shows login.php or get browser error too many redirect loops.
loginrequiredb.php is this file name
<?php
//calling connection to database
include "connection.php";
//start session
//session_start();
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0)
{
//create session named username that is equal to content of $user
$_SESSION['user']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
session for top of admin pages with lots of commenting out as tried more times than can count!
adminmain.php is this file name
<?php
session_start();
include 'includes/loginrequiredb.php';
if(!isset($_SESSION['user'])==' '){
header("location: login.php");
//}else {
//session_destroy();
//header("location: adminmain.php");
//die();
}
?>
This statement will never work.
You're checking if 'user' exists in $_SESSION (true or false) == ' '. True or false will never == ' ' and therefore you will always redirect to your other script.
if(!isset($_SESSION['user'])==' '){
Change it to:
if(!isset($_SESSION['user'])){
The general workflow should be something like this:
User hits login page
User submits credentials -> Posts to self
Login page detects credentials were entered and validates them
Valid credentials send the user to the "admin" script (and credentials need to be revalidated with every call)
Invalid credentials sends the user back to the login page.
I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)
I have created a user authentication system with necessary DB tables and php.
THe first time before I login (Before any SESSION is created) the redirect on every page works perfect (ie Redirects to the login page if not logged in).
But once I login with a user and then logout the same doesnt work. I think it might be a problem with not ending the SESSION (Sorry if am wrong)
Here are some pieces of the code in each Page
Login PHP
<?php
session_start();
$message="";
if(count($_POST)>0)
{
include('config.php');
echo $_POST['username'];
$result = mysql_query("SELECT * FROM members WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["id"] = $row[ID];
$_SESSION["username"] = $row[username];
$_SESSION["password"] = $row[password];
$_SESSION["mname"] = $row[mname];
$_SESSION["fname"] = $row[fname];
date_default_timezone_set("Asia/Calcutta");
$lastlog=date("d/m/Y");
$logtime=date("h:i a");
$query = "UPDATE `members` SET `lastlogin`='$lastlog',`logintime`='$logtime' WHERE `ID`='$row[ID]'";
mysql_query($query);
$_SESSION['logged'] = TRUE;
}
else
{
echo "<SCRIPT>
alert('Wrong Username/Password or Awaiting Approval');
</SCRIPT>";
header("Location:login_failed.html");
}
}
if(isset($_SESSION["id"])) {
header("Location:member/myprofile.php");
}
?>
PHP code on every page
<?php
session_start();
include('config.php');
if(!$_SESSION['logged'])
{
header("Location: ../login.html");
exit;
} ?>
And Finally Logout
<?php
session_start();
unset($_SESSION["id"]);
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["mname"]);
unset($_SESSION["fname"]);
header("Location:../login.html");
?>
Is there any problem with my Code. Am i missing something? I couldn't get it right. Pls Help
Thanks guys got it solved..
Now can you tell me How I can redirect login.php to user home page(myprofile.php) in case the User is logged in (Session exists) - Like facebook,gmail etc
Instead of calling unset() on each session var, you can simply use session_destroy(), which will destroy all of the current session data.
session_start();
session_destroy();
header("Location:../login.html");
For complete destructive power, you might also want to kill the session cookie:
setcookie(session_name(), '', 1);
See this question for a more complete example of session logout.
You need to unset $_SESSION['logged']
Also you should reference keys in the $row variable with strings. Eg $row['username'];.
Turning on E_NOTICE level warnings with error_reporting will help you with this.
If you haven't already, reset the session login
unset($_SESSION['logged']);
Or just change it to false
$_SESSION['logged'] = false;
When you are directly hitting a page in address bar for the first time then its a new request which goes to the server and server checks for existing session as written in your code. But its not same when you are pressing back button after logout. In this case there is no request is going to the server instead the request is fetched from browser cache. If you want to disable this situation then you have to tell browser explicitly to not to store your page in cache memory. For more detail please go through this link
using mysql as database. I got this code from the previous answers to the same question:
session_start()):
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
Could you please explain what is: $_SESSION['loggedin'] .
Where could I define it? the loggedin, please help
http://www.php.net/manual/book.session.php
I hope it will help you ;)
$_SESSION is a super-global array (available anywhere) that store all sessions variables.
session_start(); // begins session
$_SESSION['user_id'] = 99;
So, the loggedin variable is set to true when a user logged in, and then it is stored in the session. Sessions are basically information that are saved on the server.
$_SESSION is simply a persistent container where you can store anything and retrieve it in other requests during the same session. As such, you would have to set $_SESSION['loggedin'] and $_SESSION['username'] at the point where the user has successfully logged in.
You use sessions to store userdata to pass it between all pages that get loaded. You can define it as said by others by using the $_SESSION['sessionname'] var.
I will post a simple script below how to let people login on the website since you wanted to know how to use it:
session_start(); #session start alwas needs to come first
//Lets make sure scriptkiddies stay out
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
//Read the user from the database with there credentials
$query = mysql_query("select id from user where username = $username and password = $password");
//Lets check if there is any match
if(mysql_num_rows($query) > 0)
{
//if there is a match lets make the sessions to let the user login
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
}
This is a simple script how to use a Session for a login system. There are many other ways you can use sessions
After login:
$_SESSION['loggedin'] = true;
That's it.