Wrong session value when reading - php

I have got this strange problem. I wanted to make a page which uses a Username to identify which content should be displayed. It seems to work fine, except for one thing. The wrong value is read from the session on one specific page. I have checked the session value in my browser, but there the value seems to be correct. I'll show you the code:
this is my login function, using php:
<?php
//CONNECT TO DATABASE
$db = mysqli_connect("localhost","root","MyPassword","MyDBName");
if($db->connect_errno){
die('connection error: ' . $db->connect_errno);
}
//CHECK IF LOGIN DATA IS SUBMITTED AND IS CORRECT
if(isset($_POST['action'])){
switch($_POST['action']){
case "login":
$pw = $_POST['pw'];
$loginUn = $db->real_escape_string($_POST['loginUn']);
$result = mysqli_query($db,"SELECT `Password` FROM `accounts` WHERE `Username`='" .$loginUn. "'");
if(mysqli_num_rows($result) != 0){
$dbpw = $result->fetch_object();
$VI = explode("-",$dbpw->Password);
$dbpw = openssl_decrypt($VI[1],"blowfish","",0,$VI[0]);
if($pw == $dbpw){
$login = true;
$_SESSION['login'] = true;
$_SESSION['Username'] = $_POST['loginUn'];
$un = $_POST['loginUn'];
}
}
break;
case "logout":
$_SESSION['login'] = false;
$_SESSION['Username'] = "";
break;
}
}else{
if(isset($_SESSION['login'])){
$login = $_SESSION['login'];
$un = $_SESSION['Username'];
}
}
?>
it seems to work fine, since it works in the page it is used.
I have made some dummy accounts in the database, with these usernames: Admin and User.
Here is the code of the page it went wrong:
PHP:
//THIS IS NOT THE SAME PAGE AS THE PREVIOUS PHP CODE
$login = false; //CHECK IF USER HAS LOGGED IN
$un = "";
if(isset($_SESSION['login'])){
$login = $_SESSION['login']; //IF LOGGED IN SET TO SESSION VALUE
$un = $_SESSION['Username']; //SET $UN TO USERNAME IN SESSION
}
Then I used javascript and php to alert the values which the variables contain:
<script type="text/javascript">
alert("$un = <?php echo $un;?>");
</script>
With the login variable seemed to be no problem, since it had the good value, but the variable $un was wrong. When I wasn't logged in, it had no value, which is correct, but when I was logged in, it contained the value Admin, even when I wasn't logged in with Admin. In the browser options the cookie value seemed correct. I've checked the cookie on every page, and it worked just fine, just not on this page. What am I doing wrong that makes the browser(which is firefox by the way) think that it is always Admin that is logged in?

As mentioned earlier in the comments, there are many security risks in your script.
You should take a look at PHP's sessions to build your login. Using sessions, there will be only one cookie storing an ID and all the data will be stored on your server and can't be modified by the user.
Your problem with 'Admin' staying as cookie value could be a caching problem.

I just found out what I did wrong. A piece of code which I found irrelevant, missed a = so the variable wasn't compared, but set to this wrong value.

Related

Implementing a check for user levels

I'm attempted to create a login authentication system using PHP. So far I've managed to query the DB to check if a username/password given by the user matches any rows in the DB. However I have a column in the DB named "isadmin" which stores a boolean value. I want to implement a check if true/false. Depending on the result depends on which php file is loaded (included).
EDIT: I have two php files, both containing the same HTML displaying the index page of a website. However, one php file is for regular users, the other is for admin users which will contain added features. When a user enters their username and password, I want a check for the user level of that login, Once the check is done it should show the appropriate php page.
$stmt = $pdo->prepare('SELECT * FROM Reg_User WHERE username = :username AND password = :password');
$details = [
'username' => $_POST['username'],
'password' => sha1($_POST['password'])
];
unset($_POST['submit']);
$stmt->execute($details);
if ($stmt->rowCount() > 0) {
$user = $stmt->fetch();
$_SESSION['loggedin'] = $user['user_id'];
echo 'Logged in as ' . $_POST['username'];
include 'index.php';
}
else {
echo 'Sorry, your username and password could not be found Please <a href="login.html">try again
or register!</a>';
}
A simple if/else statement will do it.
if ($user["isadmin"]) {
echo "Logged in as an admin.";
#you can include your related php page here.
} else {
echo "Logged in as an user.";
#you can include your related php page here.
}
There's no sanitizing of user input in your code, this is a must in a login system, try this after your login form.
info: I don't use PDO, $con is the MYSQLI connection.
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
Your site should be set to https only, if it is ignore this link: htaccess redirect to https://www and you should be providing either a secure session cookie or a secure persistent cookie for users who are able to log in successfully. The code underneath this paragraph should be at the very top of your page before any html. This example is for time related persistent https secure cookie set to 1 day after which it will expire. You could use a session cookie but I find this annoys people if they frequent your site quite often, they don't want to have to log in again the same day if they close and reopen a browser or tab.
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
The above code is will set a secure cookie using a function because you only want it firing after a successful login. The name of the cookie really should be random and unique, something based on microtime would work well. Make sure it's not anything important which could identify the user!IMPORTANT: the name of the cookie for reference should be created at the time of account creation and added to the users table so you can identify users and represent their login details.
Standard security measures should also include a separate table of the ip, time, date and username of who logged in. If your site is busy the table will fill quickly so you could set a cron job to clean old records to keep the size down, in that case you will need to add a column for datetime to identify the age of records.
Handling the login...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
Retrieving the cookie to authenticate users...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
Here's a link for obtaining IP's: How to get the client IP address in PHP

PHP Session ending automatically

I do a lot of work using PHP frameworks but I am now building a simple login system from scratch and I am stumped. I am using PDO for my database queries. I have a simple login form which points to the same page using $_SERVER['PHP_SELF']. Then I have this code...
<?php
//LOG IN
if($_POST['login_submit']){
$username = $_POST['username'];
$password = $_POST['password'];
//Query
$database->query("SELECT * FROM users WHERE username = :username AND password = :password");
$database->bind(':username',$username);
$database->bind(':password',$password);
$rows = $database->resultset();
$count = count($rows);
if($count > 0){
session_start();
//Assign session variables
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['logged_in'] = 1;
} else {
$login_msg[] = 'Sorry, that login does not work';
}
}
When I login, its fine. It starts the session. But as soon as I go to another page the session is broken. I suspect maybe cause the session_start() is in the if($_POST['login_submit']) condition. But I could sware Ive done it like this before. Any help would be awesome..thanks!
The first line of your code...
if($_POST['login_submit']){
Only, if you submit your login form, the session is started.
And, on all other pages, you have to call session_start() ...

Trying to login via php not working scripts

Hi I am trying to get the user signed in via sessions, here is my code it was working before now it isn't i didnt even change the code.
profile.php (to show after logged in)
<?php
ob_start();
session_start();
$userName = $_SESSION['username'];
$userid = $_SESSION['userid'];
if(isset($_GET['session'])) {
$currentSessionID = $_GET['session'];
$currentSessionID = md5(md5(md5($currentSessionID)));
session_id($currentSessionID);
header("Location:profile.php");
return;
}
if(!isset($userName)){
echo "OUT";
return;
}
...
scripts/signin.php
ob_start();
session_start();
include"config.php";
echo "here";
// check for required fields
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Username']) && isset($_POST['Password'])) {
$user = mysql_real_escape_string($_POST['Username']);
$pass = mysql_real_escape_string($_POST['Password']);
$decrypt = md5(md5(md5($pass)));
$ensure = "select * from userinfo WHERE Username = '$user' and Password='$decrypt' and status='1'";
$result= mysql_query($ensure);
if(mysql_num_rows($result) > 0) {
echo "here2";
$entry = mysql_fetch_array($result) or die(mysql_error());
$_SESSION['username'] = $entry['Username'];
echo $entry['Username'];
$_SESSION['userid'] = $entry['Id'];
$currentSessionID = session_id();
$currentSessionID = md5(md5(md5($currentSessionID)));
header("Location: http://www.myprocity.com/profile.php?session=".$currentSessionID);
echo "here3";
the reason why im passing in the session id is because im trying to only keep sign in and sign up HTTPS while the other pages HTTP so I can show Google ads, does anyone know how to implement this without security issues (perfectly)
it always goes to OUT even when $_SESSION is my username (database is correct)
In profile.php you are checking for the presence of a session ID, and changing the session ID if you find it. You are doing this after you've set up a session with session_start(), but the PHP manual specifically says you must call session_id() before session_start() for this to work.
You're also hashing $_GET['session'] before sending it, and again before using it. The session ID you're trying to use in profile.php won't match the session ID used in signin.php
The result is that $_SESSION does not have the data in it you are expecting.
You need to rationalise your use of session_id(), and ensure the correct value is passed from page to page. All the hashing with md5() is just complicating matters - drop it. Realistically, I don't see why you need anything more than session_start() at the top of each page and let PHP handle the sessions. You may have an argument for doing what you're doing, but your solution simply won't work.

Session not being saved after logging in

Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.

Recurring redirect error

I have posted a question for this a long time ago, but i still can't find a answer. Basically, when a user has logged into the account and has been inactive for a while and when they return they would click something and then the system would log them out and they would have to re-login. It works 90% of the time, but sometimes it gives an error like: This page is redirecting in a way it will never complete.
But when a user clears the cookies it works fine and sometimes closing the tab and opening up a new one works too.
Here's the code:
<?php
$SUBDOMAIN = mysql_real_escape_string($_GET['p_name']);
$pname = mysql_real_escape_string($_GET['p_name']);
echo "$p_name";
include("db.php");
?>
<?php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
$ugData = $_REQUEST['p_name'];
if($_POST)
{
$_SESSION['user_name']=$_POST["user_name"];
$_SESSION['password']=$_POST["password"];
}
$secret = $info['password'];
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT user_name, password FROM accounts WHERE user_name = '$username' and p_name='$ugData'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if (# $info['password'] != $pass)
{
}
else
{
header("Location: home.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit']))
{
// if form has been submitted
// makes sure they filled it in
if(!$_POST['user_name'] | !$_POST['password'])
{
die('You did not fill in a required field.');
}
//checks it against the database
if (!get_magic_quotes_gpc())
{
$_POST['user_name'] = addslashes($_POST['user_name']);
}
$check = mysql_query("SELECT user_name,password FROM accounts WHERE user_name = '".$_POST['user_name']."' and p_name='".$ugData."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0)
{
die('That user does not exist in our database. <a href=add.php>Click Here to Register</a>');
}
while($info = mysql_fetch_array( $check ))
{
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
//gives error if the password is wrong
if (# $_POST['password'] != $info['password'])
{
die('Incorrect password, please try again');
}
else
{
// if login is ok then we add a cookie
$_POST['user_name'] = stripslashes($_POST['user_name']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['user_name'], $hour);
setcookie(Key_my_site, $_POST['password'], $hour);
//then redirect them to the members area
header("Location: home.php");
}
}
}
else
{
// if they are not logged in
?>
</table>
</form>
<?php
}
?>
Hey, your code formatting is really bad no fun to read you might want to fix that. :)
I just had a quick look at it, erros occurring only 90% or sometimes hard to catch.
I saw you are using header("Location: home.php"); without any exit; at the end, which is generally a bad idea unless you intent to do so.
The function call header("Location: home.php"); will not stop the script from processing. The user might get the header and redirects and stops code from processing (depending on some php settings) but maybe some cookies get set before the user gets redirected. So try adding a exit; after your redirect header calls.
format you code
I would wager a guess that this has to due with the differing expire times of your session cookie, and the expire times you set for your ID_my_site and Key_my_site cookies. If not overridden, the default session timeout is 30 minutes (expressed as seconds in the settings - so 1,800). Your cookies are set to expire after an hour. So you could find yourself in a situation where the session has expired, but the other cookies are still present. Depending on the order / way you are checking things and then redirecting, you will encounter this situation if the user was idle for more than 30 minutes but less than 1 hour.
Since the only redirect you are performing in this code sample is the one to home.php, there is some sort of check occurring in that file, that is sending them on the never ending redirect spiral.
As an aside, that code sample really is very messy. You are assigning and reassigning the $username variable so often for example (and to seemingly different types of things - though I wouldn't know without seeing actual input), that it is no wonder you are having mystery issues. These few lines for example are redundant:
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
You're assigning $username from the session and immediately assigning it back.
From the beginning of the file:
$SUBDOMAIN = mysql_real_escape_string($_GET['p_name']);
$pname = mysql_real_escape_string($_GET['p_name']);
These two variables are assigned the same $_GET value, but it doesn't appear that $SUBDOMAIN is ever used.
And from the end of the file you are assigning the same value twice:
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
I really would encourage you to step back from your code, look at your inputs and figure out what you need to accomplish and refactor or rewrite this code entirely. With stuff like this floating around it is no wonder you have mystery bugs in your system.
Additionally, a HTTP Location header requires the URL to be absolute. You should use something like this:
$currentServerHost = $_SERVER['HTTP_HOST'];
$currentBaseURI = $currentServerHost . rtrim(dirname($_SERVER['PHP_SELF']), '/\');
header( 'Location: ' . 'http://' . $finalURI . '/home.php' );
exit;

Categories