Okay when I log in as user 1 my PHP SESSIONS will stay logged in as user 1 until I leave or refresh the page and magically I'm logged in as user 2. What can be causing this problem?
Here is what I have at the top of all my pages.
ob_start(); // Start output buffering.
session_start(); // Initialize a session.
Here is some more code.
ob_start(); // Start output buffering.
session_start(); // Initialize a session.
$page = 'title';
include ('../includes/header.php');
require_once ('../includes/config.inc.php');
require_once ('../mysqli_connect.php'); // Connect to the db.
$mysqli = mysqli_connect("localhost", "aff", "adad", "adad");
if (!isset($_SESSION['user_id'])) {
$url = BASE_URL . 'index.php'; // Define the URL.
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
Are you destroying the sessions if you are logging in as user 2?
Related
Is it possible to use a session in PHP to track how long a user has not been active (no movement/scrolling/clicking) for. Without having to include the php script in the top of every single page throughout the website. For example in my login script I set some session variables after a successful login:
login script:
if ($pwdCheck == true) {
// Starting a session now to be able to create the variables!
session_start();
// Then creating session variables.
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['last_login_timestamp'] = time(); // testing this one here
}
Then in the top of each page throughout the website I have this:
<?php
require 'header.php'; // This includes my db login details
if((time() - $_SESSION['last_login_timestamp']) > 10){
echo $_SESSION['last_login_timestamp']; //nothing echo's at the mo
header('Location: scripts/logout-script.php');
}
?>
Logout script:
<?php
session_start();
session_unset();
session_destroy();
header("Location: ../index.php");
?>
Is this safe enough to use and is there a more efficient way of checking how long a user has been inactive for, than pasting the if((time() statement script in the top of each file?
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'
?>
I am trying to set a session variable but it's not working. Here is what I am doing in Code. Please suggest what's wrong:
Login-Validator.php
<?php
session_start();
$userName = "test";
$_SESSION['iUsername'] = $userName;
header("Location: http://www.XXXXXXXXXXXX.com/LoginSuccess.php");
?>
LoginSuccess.php
<?php
session_start();
$User = $_SESSION['iUsername'];
echo $User;
?>
Try this (put a 'exit' after the redirect)
session_start();
$_SESSION['session'] = 'this is a session';
header('location: apage.php');
exit;
read more at # PHP: session isn't saving before header redirect
If this doesnt work..comment out the redirect and open each page in a different browser tab. Then open Login-Validator.php and then open LoginSuccess.php and check if the session was set. I think it cause by the cookie not setting before the redirect.
Also is Login-Validator.php and LoginSuccess.php on the same domain?
header("Location: /LoginSuccess.php");
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();
}
?>
I'm testing the implementation of a security check in my PHP sessions. I can successfuly detect whether the session was started from another IP address and I can successfully start a new session. However, the data from the old session gets copied into the new one! How can I start a blank session while preserving the previous session data for its legitimate owner?
This is my code so far, after lots of failed attempts:
<?php
// Security check
if( isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address'] ){
// Check failed: we'll start a brand new session
session_regenerate_id(FALSE);
$tmp = session_id();
session_write_close();
unset($_SESSION);
session_id($tmp);
session_start();
}
// First time here
if( !isset($_SESSION['ip_address']) ){
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['start_date'] = new DateTime;
}
The official documentation about sessions is terribly confusing :(
Update: I'm posting some findings I got through trial and error. They seem to work:
<?php
// Load the session that we will eventually discard
session_start();
// We can only generate a new ID from an open session
session_regenerate_id();
// We store the ID because it gets lost when closing the session
$tmp = session_id();
// Close session (doesn't destroy data: $_SESSION and file remains)
session_destroy();
// Set new ID for the next session
session_id($tmp);
unset($tmp);
// Start session (uses new ID, removes values from $_SESSION and loads the new ones if applicable)
session_start();
Just call session_unset after session_regenerate_id to reset $_SESSION for the current session:
if (isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address']) {
// Check failed: we'll start a brand new session
session_regenerate_id(FALSE);
session_unset();
}
when a new user connects to your server, the script should only be able to access that user's session variables. you will want to store other info in a hashed session variable to verify that the session is not being jacked. if it is being jacked, no reason to start a new session, maybe just exit the script with a warning.
here is the function a lot of people use for fingerprinting a session:
function fingerprint() {
$fingerprint = $server_secure_word;
$fingerprint .= $_SERVER['HTTP_USER_AGENT'];
$blocks = explode('.', $_SERVER['REMOTE_ADDR']);
for ($i=0; $i<$ip_blocks; $i++) {
$fingerprint .= $blocks[$i] . '.';
}
return md5($fingerprint);
}
Use this
unset($_SESSION['ip_address'])
instead of 'unset($_session)'
You can also use session_destroy.
session_destroy will destroy session data. For example,
session_start();
$_SESSION["test"] = "test";
session_write_close();
session_start();
// now session is write to the session file
// call session_destroy() will destroy all session data in the file.
session_destroy();
// However the you can still access to $_SESSION here
print_r($_SESSION);
// But once you start the session again
session_start();
// all session data is gone as the session file is now empty
print_r($_SESSION);
will output
array([test] => "test")array()