PHP SESSION Conflicts - php

I have this in my $_SESSION setting script:
<?php
//----------------------// Start session----------------------
if(!isset($_SESSION))
{
session_start();
}
//------------------------------------------------------------
//------------------// Check if Username $_SESSION is set------------------------------------------
if (!$_SESSION['Username']) { // If not current User
header("Location: ./logout.php"); // Session destroy file that leads to session logout landing page
exit();
}
//------------------------------------------------------------
?>
Now, what I basically do is just check if Username SESSION is set. But, I have come to notice something strange while putting another user through:
If we click the same link at the same time and arrive on the landing page same time, I noticed I can see my Username displayed as his Username and his personal data like email and phone replaced mine in my very own PC! This is really strange to me as we do not even live in the same country or even share same PC.
So, it is obvious I have not secured my SESSION and I have used a lame approach without thinking about security and this can be abused with SESSIONS hijacked.
How do I resolve this conflict? How do I restrict each logged in user to a particular session without conflicts if two or more users access the same resource at the very same time? I need help. I can't sleep since I found this.
After reading your responses, I will now show a snippet of the functions.php file which outputs Use data from DB.
First, I get the UserName value from session using:
$UserName = $_SESSION['Username'];
With this value, I query DB to get more user details:
//------------Get User Info -- All user column
$Get_User_Info = mysqli_query($conn,"SELECT * FROM customers WHERE User='$UserName'");
/************************************************************/
/************************************************************/
$Get_User_Info_row = mysqli_fetch_array($Get_User_Info,MYSQLI_ASSOC);
/************************************************************/
//---- Now list all user rows
$GLOBALS['Skype'] = $Get_User_Info_row['Skype'];
$GLOBALS['Jabber'] = $Get_User_Info_row['Jabber'];
$GLOBALS['ICQ'] = $Get_User_Info_row['ICQ'];
$GLOBALS['Join_Date'] = $Get_User_Info_row['Join_Date'];
$GLOBALS['Join_Date_Time'] = $Get_User_Info_row['Join_Date_Time'];
$GLOBALS['Balance'] = number_format($Get_User_Info_row['Balance'],2);
The above is what is contained in the functions.php which I require with each page I need protected.
As you can see, I barely see where I have done too much wrong there.

Related

Redirect loop on login script PHP

I have a login system that whenever the user logs succesfully creates some cookies with his username password and some other variables that are put in the url for configuration of the session:
setcookie("username", $myusername); //Sets a cookie storing the username
setcookie("password", $mypassword); //Sets a cookie storing the encrypted value of the password
setcookie("typeOfUser",$type); //example variable
and the variables are passed through the URL:
header("location:http://www.example.com/logged.php?type=".$type);
inside the logged.php page I have a file called protect.php which checks whether the cookies exist and what kind of user is it.
if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){
//check if this user's cookies exist on the DB
$user = $_COOKIE["username"];
$pass = $_COOKIE["password"];
$sql="SELECT * FROM USERS WHERE Usr='".$user."' and Pass='".$pass."';";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
$type = $_COOKIE["type"];
header("location:logged.php?type=".$type);
exit();
}
else{
header("location:http://www.example.com/login.php");
}
}
so if the user just types www.example.com/logged.php he/she will get the variables associated with his user, but whenever I do this I get a redirect loop on the site. (It seems to me a little bit obvious that it redirects cause each time it goes to the header("location... it restarts and at the top it checks the protect.php... but I can't figure out a way to solve this).
Note logged.php just has at the top an:
include("protect.php");
Thanks in advance!
The reason that this script loops infinitely is based in the logic:
if($count==1){
header("location:logged.php?type=".$type);
}
else{
header("location:http://www.example.com/login.php");
}
Regardless of the value of $count at this point, your script will send a location header. In other words, the browser is receiving a redirect either way, whether $count is equal to 1 or not.
if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){
In combination with this line, your loop is defined. This evaluates to true if the user has these cookies defined, which happens when they are logging in for the first time, or have already logged in. If they are logged in, their username and password must be valid, and $count will end up as 1, because they are in the database.
In short, every time the user goes to logged.php after they are logged in, this script is run because they have the appropriate cookies and they are directed, again, to "logged.php?type=."$type" (over and over again) because they are a valid user and present in the database.
To fix this, you'll want to stop header("location:logged.php?type=".$type); from running every time protect.php is run. This is the essence of your problem. You can fix this however you like, but I would do it with sessions.
Check out this tutorial to learn how to implement sessions in your logins script.
You already have three cookies: username, password, and typeOfUser. The system you have works fine, but most authentication scripts use sessions, accessible like cookies ($_COOKIE['foo']), but with the $_SESSION variable instead. The advantage to using session is that the values you store in them are not available to anyone but scripts on your server/site, to view, or to edit. In general, the less information you expose to the user, the better. If you need clarification, check out this StackOverflow post or the basic examples on the PHP website.
One more thing to point out is in your script, if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){ has no else statement. If one or both of these cookies are not defined, no code will be executed, and what I am assuming is a protected page will be displayed publicly. You may want to add an else statement, something along the lines of:
else{
header("location:http://www.example.com/login.php");
}
Hope you're able to make this functional and awesome!

PHP: Sending a constant through a form and auto-sending it

For a website, I need to route users to their own page. I have a login form, which sends data to a PHP file to check if the user's information is correct, and if so, forwarding the user to their page. The only problem is that I need to validate the user on arrival, to check if they logged in or just typed out the URL. I plan to use this with a POST, but how can I auto-send the constant (i.e. "logged-in")? Is there a way to do that through an HTML form (outputted from an echo) and sending it when the page loads? Thanks in advance!
EDIT 1: I understand that I must use Sessions, but whenever the page redirects it clears the session. The whole reason I was asking this was because I needed a way to keep the session active. How do I redirect in a way that doesn't clear the session?
In the PHP file that validates their credentials, start a "session". You can then apply session variables that can be called at any time while the session is valid. You can do this with POST, which is sounds like you're using, or by querying a database upon validation.
For example, upon validation:
session_start();
$_SESSION['username'] = $_POST['username'];
$security_check = mysql_query("SELECT * FROM userList WHERE username = '$username'");
$row = mysql_fetch_assoc($security_check);
$_SESSION['userId'] = $row['userId'];
$_SESSION['userFullName'] = $row['userFullName'];
On subsequent pages, you can put the following code at the top to check if the user logged in. If not, it will kick them back to the index page; otherwise the $_SESSION variables will be maintained.
<?php
session_start();
if (!isset($_SESSION['userId'])) {
echo "<script> window.location.replace('index.php?login=no') </script>";
}
?>
As suggested in the comments, I would recommend doing some further research on sessions to get a full understanding of how they work.

session set in folders php mysql

i have this code:
$username = $_POST["username"];
$password = $_POST["password"];
if(mysql_num_rows($result80)>0)
{
$row80 = mysql_fetch_assoc($result80);
$_SESSION["loginmng"] = 1;
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
$fname = $row80["fname"];
$lname = $row80["lname"];
$userid = $row80["id"];
}
and every thing is ok because i tryed to echo the session and its work in the same page (index.php)
now i have this check:
if(($_SESSION["loginmng"]!=1)||(!isset($_SESSION["username"]))||(!isset($_SESSION["password"])))
{
header("Location: index.php");
}
when i put this into new folder:
newfolder/index.php
the check is not working right,when i have logged in , and the session is set....when i am tring to echo $_SESSION["loginmng"] and the other sessions,,its values is empty like no session setted and the header is got run ...and go to index...i have put session_start(); in the first php line too
i tryed too:
if($_SESSION["loginmng"]!=1)
{
header("Location: ../index.php");
}
and the same thing...like no session set, what may be the problem
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag.
Maybe you forgot to add session_start(); on top of the file.
To make session start on each page you need to start the session on each page.
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.

Force user to logout session PHP

I can't seem to find a straightforward answer to this question. Is there a way in which I can force a logged in user to logout? My login system essentially just relies on a session containing the user's unique ID (which is stored in a mysql database). So essentially just...
if (isset($_SESSION['user_id'])) {
echo "You're logged in!";
} else {
echo "You need to login!";
}
But let's say I want to ban this user, well I can change their status to banned in my database but this won't do anything until the user logs out and attempts to log back in... So, how do I force this user to logout? Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server. Any help is appreciated, thank you.
Either you need to check every time they load a page, or possibly look at an Ajax call at set intervals to check their status from the DB.
Then you can use session_destroy(); to end their session. This will destroy their entire session.
Otherwise you can use unset($_SESSION['user_id']); to unset a single session variable
Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server.
Loading the user from the database on every page load, rather than storing a copy of the user in the session, is a perfectly reasonable solution. It also prevents the user from getting out of sync with the copy in the database (so that, for instance, you can change a user's properties or permissions without them having to log out and back in).
Try to put this on every page...
if (isset($_SESSION['user_id'])) {
$sql = "SELECT from tbl where status='banned' and user_id=$_SESSION['user_id'] ";
$query = mysql_query($sql);
if(!empty(mysql_num_rows($query))){ // found the banned user
//redirect to logout or
//session_destroy();
}
} else {
echo "You need to login!";
}
if the user is still logged in... check if his/her status is banned or not... if banned.. then logout
You can unset it.
unset($_SESSION['user_id'])
You could use Custom Session Handlers this way you have full control where and how the session data is stored on the server.
So you could store the session data for a particular user in a file called <user_id>.session for example. Then, to logout the user, just delete that file.
Ajax calls in an interval will put extra load on server. If you want real-time response to your actions(e.g. the user will be signed out right when you ban them from your system backend), then you should look into something like Server Push.
The idea is to keep a tunnel open from Server to Browser whenever a user is browsing your website, so that you can communicate with them from server-side too. If you want them to be banned, push a logout request and the process that in your page(i.e. force logout by unsetting session).
This worked for me am using pHP 5.4
include 'connect.php';
session_start();
if(session_destroy())
{
header("Location: login.php");
}
You can use session_save_path() to find the path where PHP saves the session files, and then delete them using unlink().
Once you delete the session file stored in the sever, the client side PHPSESSID cookie will no longer be valid for authentication and the user will be automatically be logger out of your application.
Please be very careful while using this approach, if the path in question turns out to be the global /tmp directory! There's bound to be other processes other than PHP storing temporary data there. If PHP has its own directory set aside for session data it should be fairly safe though.
There is a few ways to do this the best in my opinion based on security is:
NOTE: THIS IS REALLY ROUGH.... I know the syntax is wrong, its just for you to get an idea.
$con = mysql_connect("localhost","sampleuser","samplepass");
if (!$con)
{
$error = "Could not connect to server";
}
mysql_select_db("sampledb", $con);
$result = mysql_query("SELECT * FROM `sampletable` WHERE `username`='".$_SESSION['user_id']."'");
$userdeets = mysql_fetch_array($result);
if($_SESSION['sessionvalue'] != $userdeets['sessionvalue'])
{
session_destroy();
Header('Location: logout.php');
}
else
{
$result2 = mysql_query("UPDATE `sessionvalue` WHERE `username`='".$_SESSION['user_id']."' SET `sessionvalue` = RANDOMVALUE''");
$sesval = mysql_fetch_array($result2);
$_SESSION['sessionvalue'] = $seshval
}
Now I know thats not the very code but in essence what you need to do to be secure and have this ability is:
Everytime a page load check a Session value matches a value in the DB.
Every time a page loads set a new session value based on a random generated DB value. you will need to store the username in a session as well.
if the Session ID's do not match then you destroy the session and redirect them.
if it does match you make the new session ID.
if you want to ban a user you can set their sessionvalue in the DB to a value like "BANNED". this value will not allow them to log in either. this way you can control user through a simple web form and you can also generate list of banned users very easily etc etc. I wish I had more time to explain it I hope this helps.

Why does my session-based login system not work?

I have just started learning PHP, and I wrote an account system with PHP and mySQL for my website. I know the sql stuff is working fine, the problem is my PHP session.
When I go to test it, I can try to login, and it fails. Then, I try to login again, and it will succeed. It always succeeds on the second attempt to login. It never succeeds on the first attempt in Firefox, but it does in Chrome. Also, a couple of times in Chrome, after I succeeded in logging in, going to a some different pages on my site seemed to erase the session. Or, at least, that session was not registering on those other pages. I didn't have that problem on Firefox. I have checked, double-checked, and triple-checked, and all of my pages call session_start() before anything else, so I know that can't be the problem.
I must not have a full enough understanding of PHP sessions, as it's just not working consistently.
After posting this, I tested in IE, and everything works fine there. I log in on the first attempt, and any page I visit maintains my session.
Here is the code for the php script that actually "logs in" the user:
<?php
session_start();
//pass info to mysql(servername, username, password)
$connect = mysql_connect ("localhost", "ggstudio", "mtgertai1");
if (!$connect)
{
die ('Failed to connect: ' . mysql_error());
}
mysql_select_db("ggstudio_accountDatabase", $connect);
//capture data sent to page through login
//usernameField and passwordField
$usernameSubmission = $_POST[usernameField];
$passwordSubmission = $_POST[passwordField];
$validAccount = mysql_query("SELECT * FROM userAccounts WHERE userID = '$usernameSubmission' AND userPassword = '$passwordSubmission'");
$row = mysql_fetch_array($validAccount);
if (($row['userID'] == $usernameSubmission)&&($row['userPassword'] == $passwordSubmission))
{
/*********************************
**********************************
assign global variables to session
after starting session and then***
redirect to user homepage*********
**********************************
**********************************
*/
//get account number from database
$_SESSION['accountNumber']= $row['accountNumber'];
//get first name from database
$_SESSION['firstName']= $row['firstName'];
//get last name from database
$_SESSION['lastName']= $row['lastName'];
//save username into session
$_SESSION['username']= $row['userID'];
//save password into session (only really useful if user wants to change password)
$_SESSION['userPassword']= $row['userPassword'];
//get user's email address from database
$_SESSION['userEmail']= $row['userEmail'];
//get GP from database
$_SESSION['gpoints']= $row['userGloryPoints'];
//get user join date from database
$_SESSION['userJoinDate']= $row['userJoinDate'];
//get user rank
$_SESSION['userRank']= $row['userRank'];
header('Location: http://www.glorygamer.com/account_home.php');
}
else
{
$loginFailed= TRUE;
setcookie("incorrectLogin", $loginFailed, time()+20);
header('Location: http://www.glorygamer.com/shibboleth.php');
}
?>
If the session is working intermittently then I'd say there's one of two things happening:
Your session isn't being set in the browser correctly
Your session isn't being saved on the server in time.
One thing that can happen (especially when you're testing on localhost) is that an authenticated session isn't written to disk in time for the next request, hence the next request appears to be un-authenticated (remember that apache is multi-process; your second request could be handled by another process which isn't aware of what the first is doing). Here's one possible solution:
$_SESSION['userRank']= $row['userRank'];
session_write_close();
header('Location: http://www.glorygamer.com/account_home.php');
The call to session_write_close() should mean that your authenticated session is ready in time for the next request.
HTH.
The first thing I see are the lack of single quotes. Also, you should definitely escape these so that nobody can do any SQL injection on you.
$usernameSubmission = $_POST[usernameField];
$passwordSubmission = $_POST[passwordField];
should be:
$usernameSubmission = mysql_real_escape_string($_POST['usernameField']);
$passwordSubmission = mysql_real_escape_string($_POST['passwordField']);

Categories