How to prevent php sessions getting wrong values? - php

I have a php site that some times when I load a page gets $_SESSION values from another user, but when I refresh the page it's all ok.
For example, I logged in as User A, navigate through the site and then in a page I get the session from User B. I refresh the page and get again the correct info from User A.
This is the file "db.php" that use with require_once in every file in my site. I put this at the very beginning of all my scripts:
<?php
if(!isset($_SESSION)){session_start();}
$mysqli = new mysqli("localhost", "", "", "");
if ($mysqli->connect_errno) {
echo "Error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$mysqli->set_charset("utf8");
include("functions.php");
date_default_timezone_set('America/Mexico_City');
?>
Also I use a shared hosting, which has this values set:
session.gc_maxlifetime = 604800;
session.save_path = /var/cpanel/php/sessions/ea-php56;
I have a "header.php" required once in each page, that has this query to get and show the username of the current user. This is where I get noticed that something is wrong with the session, but I don't know why:
$query=sprintf("SELECT * FROM tblusers WHERE user=%s",$_SESSION['ADMINID']);
$info=$mysqli->query($query);
$c=$info->fetch_assoc();
The login is done in this way. cpass() is a function that crypts the pass to check it against the database. The login is done ok, and after some browsing I encounter the problem:
<?php
if(isset($_POST['user'])&&isset($_POST['pass'])){
$user=$mysqli->real_escape_string(trim($_POST['user']));
$pass=cpass($mysqli->real_escape_string(trim($_POST['pass'])));
$query=sprintf("SELECT * FROM tblusers WHERE user=%s AND pass='%s'",$user,$pass);
$check=$mysqli->query($query);
if($check->num_rows==1){
$r=$check->fetch_assoc();
$_SESSION['ADMINID']=$r['userid'];
session_regenerate_id(true);
header("Location: /");exit;
}
}
?>
The logout is handled this way:
<?php
if(!isset($_SESSION)){session_start();}
$_SESSION=array();
unset($_SESSION);
session_unset();
session_destroy();
if(isset($_GET['url'])){
header("Location: ".$_GET['url']);
}else{
header("Location: /");
}
?>
Thanks in advance!

Simple fix, when you have a login script that works, you can provide something like this at the end of it to give them a $SESSION tied in with their userID in your database.
Login.php
//login code
.....
//
//if successful
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /home.php" );
die();
And then at the top of your homepage ( I presume this is where you want an echo like you are logged in as 'user123'
home.php
<?php
session_start();
if(isset($_SESSION['user_id']) || isset($_SESSION['logged in'])){
echo 'whatever you want here'
?>

Related

Page won't redirect if user is not logged in

usercheck.php
// Start a session.
session_start();
// Check the database for the user.
$user_check = $_SESSION['user_username'];
$ses_sql = mysqli_query($db,"SELECT user_username FROM users WHERE user_username='$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_user = $row['user_username'];
// If the check fails, redirect to the login page.
if(!isset($user_check)) {
header("Location: /index.php");
}
I have a file indcluded on every page that is supposed to check to see if the user is logged in. If they are, it shows the page. If not, it redirects back to the index.
The problem is that it's not redirecting and I cant quite figure out why. I can easily type the URL of the page I want to go to and bypass the login completely even with this file successfully included.
Am I doing something wrong or outdated?
Edit: Example of a page containing the file.
<?php
$pageTitle = 'Dashboard';
$pageClass = 'dashboard';
include_once('./assets/template/template.php');
// Start the page content.
function getPageContent() {
global $mysqli;
// Connect to database.
include_once('./assets/include/db-connect.php');
// Check the database for the user.
include_once('./assets/include/db-user-check.php');
?>
... some html ...
<?
// Close the database connection.
$db->close();
}
?>
Try changing if(!isset($user_check)) { to if(!isset($login_user)) {. It could be that the value of $_SESSION['user_username'] isn't correct. If that isn't the case, try var_dump($_SESSION); exit(); inside your if statement and troubleshoot from there.

Destroying session for user login / NULL $_SESSION remnant

I'm trying to create a user login system for use on a website I'm building. I have the login script and register script, but I'm having trouble with the logout and destroying the sessions.
Here's my index code. It gets the database info in config (doesn't do anything with it yet), then runs check-login to make sure the user is actually logged in. It has a logout button that routes to logout.php
<?php
include_once("config.php");
include_once("check-login.php");
session_start();
$username = $_SESSION["username"];
?>
<html>
<body>
<h1>
Hello <? echo $username ?>! We're still building, but feel free to... wait?
</h1>
<form action="logout.php">
<input class="logoutbutton" type="submit" value="Logout" />
</form>
</body>
</html>
Here is my check-login.php file. Notice that anytime I link back to the index, I'm using a $_GET to post some information into the address bar. There is no place where I simply go back to index.php
<?php
ob_start();
include_once("../myreadingplanner_config/config.php");
if(($_SESSION['username']) != null){ //If user is already logged in...
$username=$_SESSION['username'];
header("Location: index.php?Message=AlreadyLoggedIn$username");
}
else {
if(isset($_POST['username']) && strlen($_POST['username'])!=0){ //if username is valid
$username = $_POST['username'];
} else {
header('Location: login.php');
}
if(isset($_POST['password']) && strlen($_POST['password'])!=0){
$password = $_POST['password'];
} else {
header('Location: login.php');
}
$SQLString = "SELECT TOP(1) * FROM Users WHERE Username = '$username' AND Password = '$password'";
$result = sqlsrv_query($conn, $SQLString) or die ("");
if($result != null)
{
$_SESSION['username'] = $username;
header("Location: index.php?Message=YouLoggedIn$username");
} else {
header("Location: index.php?Message=UserLoginNotFound&Username=$username");
}
}
ob_flush();
?>
And finally here is my logout.php, which should (in theory) destroy the session, and head back to index.php. When it gets back to index.php, index.php will reroute to login.php using the include_once("check-login.php");
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
Just looking at my logic, there SHOULD be an infinite loop in the check-login, right? Because if the user is logged in, it should reroute to index, which includes check-login, which reroutes to index, which... etc.
If you want to check out the site for yourself, please go to www.myreadingplanner.com, and use this info to login (user will be deleted eventually)
Username: StackUser
Password: password1
So functionality wise, login.php should NEVER be visible unless you have a valid session, and when it does, it should say 'Welcome $username!'. But if you hit the logout button on index, it will still keep the session open, but it will be null.
Any advice on either why logout doesn't seem to fully logout the user OR why it is logging the user out but is keeping the NULL $_SESSION around?
To remove sessions use
unset($_SESSION['SESSION_VAR'] );
session_destroy(); //closes the session and prevents session riding
For more information I'd research session riding as you should close your session as soon as you can to prevent this.
Also do not unset the entire session global array.
//don't do this
unset($_SESSION);
First, have a look at index.php file. in that file, change the code below:
include_once("config.php");
include_once("check-login.php");
session_start(); // move the session_start function and place at the top of the script
$username = $_SESSION["username"];
change it, so that it becomes like this:
session_start();
include_once("config.php");
include_once("check-login.php");
$username = $_SESSION["username"];
This problem occurs because at the file check-login.php you do not declare the function session_start();
I have tested this problem. And it works!

Allow content with $_Session

I've been following some tutorials and managed to get my login and logout scripts working. What I"m now trying to do it get it to only allow access to pages when the user is logged in. Right now it's just redirecting users to the login page every time, which tells me that the session isn't being set or or my code is just wrong (and I've tried everything I can think of)
This is the login.php script that my form runs in order to set the session:
<?php
// establishing the MySQLi connection
require 'init.php';
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$pass = mysqli_real_escape_string($conn,$_POST['password']);
$sel_user = "select * from login where username='$username' AND password='$pass'";
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['username']=$username;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Sorry. Your username or password is not correct, try again!')</script>";
}
}
?>
And this is what I'm including at the top of every page:
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: account-login.php");
}
require 'init.php';
?>
I switched the login.php file from directing to a page to a popup telling me that I logged in and I get the popup, so the user and password are registering fine, it's just not storing the session somehow. Any ideas? Thanks!
OK, so I got it to work finally!
Apart from all the comments (which helped a TON), I also decided to change the name I was setting in $_SESSION. I think it may be because the session name matched the name or POST data and that eas causing a conflict somewhere.
Changed this:
$_SESSION['username']=$username;
Which I think conflicted to this:
$_SESSION['session_id']=$username;
Worked!
THANK YOU!!!!!!!

PHP : Must login twice until session variables are set

SOLUTION: after many hours of searching, it seems this problem was occurring when I access my website without adding the "www." before the domain. so what actually was happening is, I was logging in with example.com/login.php sets session somewhere, that my member control doesn't recognize, so it redirects me back to www.example.com/login.php, that when I login everything works Ok.
when I login from www.example.com/login.php (with the www.) it logs in correctly from first attemp.
So I added a code to make sure I always have the www in the URL:
if ($_SERVER['HTTP_HOST'] == "example.com")
{
$url = "http://www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
and everything works well now. Hope it helps someone.
So, I have built over 3 websites, and all have same problem, I don't know why, I have to login twice till I'm rly logged in.. (till the session variables are set). Help is really appreciated, been trying to fix this and looking for solution since a long time...
session_start();
if ((isset($_SESSION['UserName']))&&(isset($_SESSION['LastActivity'])))
{
header ('Location: http://www.example.com/Account.php');
}
if (isset($_POST['username']))
{
mysql_connect("localhost","DBuser","pass") or
die ("could not connect to mysql");
mysql_select_db("DBNAME") or die ("no database");
$inputUserName = $_POST['username'];
$inputPass = $_POST['password'];
$datausername = mysql_real_escape_string($inputUserName);
$password=md5($inputPass);
$sqlCommand = "SELECT * FROM Members
WHERE UserName='$datausername' AND
Password='$password'";
$result = mysql_query($sqlCommand);
if (mysql_num_rows($result) > 0)
{
$_SESSION['UserName'] = $datausername;
$_SESSION['LastActivity']= time();
sleep(2);
$LoginDate = date('Y-m-d H:i:s');
mysql_connect("localhost","DBUPDATEusername","DBuserPass") or
die ("could not connect to mysql");
mysql_select_db("databaseName") or die ("no database");
mysql_query("Update Members SET LastLogin='$LoginDate' WHERE
UserName='$datausername'");
mysql_close();
echo '<meta http-equiv="Refresh" content="0;url=http://www.example.com/Account.php?p=Login_Success"/>';
}
else {
mysql_close();
echo '<div id="error_msg">Error: Information entered are not correct. Please check and try again.</div>';}
}
}
?>
<form...
login form (with action=""), and method post).
Note: I use the html refresh tag, because I can't use the header redirect.. (I get error that header is already sent).
and in the example.com/Account.php I do this check at the top of the code:
session_start();
if ((!isset($_SESSION['UserName']))||(!isset($_SESSION['LastActivity'])))
{
header('Location: http://www.example.com/?p=Must_Login');
}
And and it seems that first time I login and am redirected to account.php panel.. the session values are not set, and redirects me back to Must_Login page. I login again (same login page I use at first time. But the second time when I login, it does set the session values, and everything is OK.
Thank you very much for your help in advance!
SOLUTION: after many hours of searching, it seems this problem was occurring when I access my website without adding the "www." before the domain. so what actually was happening is, I was logging in with mydomain.com/login.php sets session somewhere, that my member control doesn't recognize, so it redirects me back to www.mydomain.com/login.php, that when I login everything works Ok.
when I login from www.mydomain.com/login.php (with the www.) it logs in correctly from first attemp.
So I added a code to make sure I always have the www in the URL:
if ($_SERVER['HTTP_HOST'] == "mydomain.com")
{
$url = "http://www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
and everything works well now. Hope it helps someone.
Connect to database before your Members select.
Start session if it has not been started yet.
Connect to the server and select the database before querying.
if (!isset($_SESSION)) {
session_start();
}
mysql_connect("localhost","DBusername","DBuserPass") or
die ("could not connect to mysql");
mysql_select_db("databaseName") or
die ("no database");
if ((isset($_SESSION['UserName']))&&(isset($_SESSION['LastActivity'])))
header ('Location: http://www.mysite.com/Account.php');
if (isset($_POST['username']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$sqlCommand = sprintf( "SELECT * FROM Members
WHERE UserName = %s AND Password = %s", mysql_real_escape_string( $_POST['username'] ), md5( $_POST['password'] ) );
$result = mysql_query( $sqlCommand );
$rowsnr = mysql_num_rows( $result );
if (mysql_num_rows( $result ) > 0)
{
$_SESSION['UserName'] = mysql_real_escape_string( $_POST['username'] );
$_SESSION['LastActivity']= time();
sleep(2);
mysql_query(sprintf("UPDATE Members SET LastLogin = NOW() WHERE
UserName = %s", mysql_real_escape_string( $_POST['username'] )));
mysql_close();
echo '<meta http-equiv="Refresh" content="0;url=http://www.mysite.com/Account.php?p=Login_Success"/>';
}
else
{
mysql_close();
echo '<div id="error_msg">Error: Information entered are not correct. Please check and try again.</div>';
}
}
?>
Try putting following code AFTER you check for the login?
session_start();
if ((!isset($_SESSION['UserName']))||(!isset($_SESSION['LastActivity'])))
{
header('Location: http://www.mysite.com/?p=Must_Login');
}
PHP sessions are written to the session handler after the script which started the session finishes execution. In your case the first script started the session and updated session variables 'username' and 'lastactivity' then redirected to another page. But still the session values are in memory - not registered to be used in the second script.
One way to fix the problem is to call
session_write_close();
before (or after) sleep(2);
for more information see here
try session_set_cookie_params(0, '/', '.domain.com') before your session_start();
I had the exact same problem, in my case I was redirecting to the website address after login:
header('Location: http://mywebsite.com');
die();
Even manually closing the session before the redirect didn't help.
I fixed it by instead redirecting to a specific page:
header('Location: index.php');
die();

sessions not being set in all pages on php5

I am using session_start(); at the top of my login page. After a user logs in, a message is displayed on screen which shows that the session is being set. But, I cannot carry sessions from page to page or can I echo out SID. It is a blank value. I would be grateful if someone could show me where I am going wrong. Thanks
<?php
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
session_start();
$_SESSION['user'] = $userpost;
}
echo $_SESSION['user'] .' '. 'Just logged in' . SID;
// Or maybe pass along the session id, if needed
?>
You have to have session_start(); on the very top of your code, after <?php. Since you are checking if the session is set without starting the sessions, your code will fail.
Is has to be like this:
<?php
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
}
echo $_SESSION['user'] .' '. 'Just logged in' . SID;
// Or maybe pass along the session id, if needed
?>
It's because you're always looking in $_POST for your user data.
Bring the session_start() out of that condition:
<?php
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
}
You said that you called session_start() at the top of your login page, but you did not mention your other pages. session_start() needs to be called at the top of every page in your application. I generally put my session_start() logic, along with a snippet of code for logging the user out after a period of inactivity, in an include file and then include it at the top of every page.
<? session_start();
if (isset($_SESSION["last_activity"]) && (isset($_SESSION["username"])) && ((time() - $_SESSION["last_activity"]) > 900))
{
unset($_SESSION["username"]);
}
else
{
$_SESSION["last_activity"] = time();
}
?>

Categories