Ok here is my problem:
When a user logs into my site I put all their user info into a session like this
session_start();
//Put all user info into session cookie
$_SESSION["login"] = 'true';
$_SESSION["id"] = $user_info['id'];
$_SESSION["firstname"] = $user_info['firstname'];
$_SESSION["lastname"] = $user_info['lastname'];
$_SESSION["screen_name"] = $user_info['screen_name'];
$_SESSION["facebook"] = $user_info['facebook'];
$_SESSION["email"] = $user_info['email'];
$_SESSION["date_joined"] = $user_info['date_joined'];
$_SESSION["account_type"] = $user_info['account_type'];
$_SESSION["account_active"] = $user_info['account_active'];
$_SESSION["hashed_password"] = $user_info['hashed_password'];
The problem is if they logged in from www.domain.com and then end up on a page at domain.com or the other way around they login from domain.com and end up on a page at www.domain.com the info stored in the session is not available.
How can I have the session info available no matter if they logged in with www or not?
# Mr. Grossman
Would it be proper to do something like this:
<?php
//Ok I modified the code so I don't get the undefined errors I was getting
//OLD CODE
//$currentCookieParams = session_get_cookie_params();
//$rootDomain = '.domain.com';
//session_set_cookie_params(
//$currentCookieParams["3600"],
//$currentCookieParams["/"],
//$rootDomain,
//$currentCookieParams["false"],
//$currentCookieParams["false"]
//);
//session_name('mysessionname');
//NEW CODE
$rootDomain = '.beckerfamily1.com';
session_set_cookie_params( 3600, '/', $rootDomain, false, false);
session_start();
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 2700)) {
// last request was more than 45 min ago
if(isset($_SESSION['id'])){
$connection = mysql_connect('localhost', '******', '*******');
if (!$connection){
die('Database connection failed: ' . mysql_error());
}
$db_select = mysql_select_db('beckerfamily');
if(!$db_select){
die('Could not select database: ' . mysql_error());
}
$query = "UPDATE users SET online='no' WHERE id='{$_SESSION['id']}' LIMIT 1";
$result = mysql_query($query);
if (!$result) {
die("Database query failed: " . mysql_error());
}
}
$_SESSION = array();
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
if(isset($connection)){
mysql_close($connection);
}
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
Also is it necessary to have session_name('mysessionname'); or can I just omit that and PHP will set the session name on its own?
Cookies (like the PHPSESSID cookie) are only available on the domain they were set on. You can make the domain include all subdomains:
ini_set('session.cookie_domain', '.example.com' );
or if configuration does not allow you to override that,
$currentCookieParams = session_get_cookie_params();
$rootDomain = '.example.com';
session_set_cookie_params(
$currentCookieParams["lifetime"],
$currentCookieParams["path"],
$rootDomain,
$currentCookieParams["secure"],
$currentCookieParams["httponly"]
);
session_name('mysessionname');
session_start();
http://php.net/manual/en/function.session-set-cookie-params.php
Even better might be to choose whether you want your site accessed through www or not, and redirect all requests to the other.
I'm not sure what language you are using, but you need to change the "domain" property of your session cookie. If you set the cookie domain to "domain.com", it will be accessible on both "domain.com" and "www.domain.com".
Related
I have an issue where some of my pages take an extended period to load due to communications with various external APIs. I noticed that when I change to a different page or reload the current page before it has finished loading, it seems to drop my session and logs me out.
For example, if loading page about.php and then I click a link to load profile.php before about.php has loaded fully, it logs me out and drops me back at the login screen.
I don't know what to search for this but have not been able to find any information on similar problems. Can anyone shed light on what would be causing this?
Top of each page:
sec_session_start();
if(login_check($dp_conn) == false)
{
header("location:../login.php?error=1");
}
sec_session_start() function:
function sec_session_start()
{
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(); // regenerated the session, delete the old one.
}
login_check() function:
function login_check($db)
{
// Check if all session variables are set
if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string']))
{
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$query = "SELECT password FROM users WHERE id = " . $user_id . " LIMIT 1";
$result = mysql_query($query, $db);
if (mysql_num_rows($result) == 1)
{
// If the user exists
$row = mysql_fetch_row($result);
$password = $row[0];
$login_check = hash('sha512', $password.$user_browser);
if($login_check == $login_string)
{
// Logged In!!!!
return true;
}
else
{
// Not logged in
return false;
}
}
else
{
// Not logged in
return false;
}
}
else
{
// Not logged in
return false;
}
}
I will add an answer as this can help others.
So using sec_session_start() will use different SESSION ID on every page request, particularly
session_regenerate_id();
If your site loads a page very slow and user opens a another link on you page while first page is not loaded fully SESSION ID will be lost hence causing a problem.
Just remove session_regenerate_id(); from sec_session_start function.
The weirdest thing is happening, when I logout of my app it redirects me to the correct page, so the script runs. However when I randomly type in a page that I should not have access to since my sessions and cookies have been destroyed I have access to it, this only happens on my hosted server, on local host it works fine, has anyone run into this before?
The start sessions script
<?php
session_start();
// If the session vars aren't set, try to set them with a cookie
if (!isset($_SESSION['user_id'])) {
if (isset($_COOKIE['user_id']) && isset($_COOKIE['user_email'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['user_email'] = $_COOKIE['user_email'];
$_SESSION['lawyer_client'] = $_COOKIE['lawyer_client'];
}
}
?>
The log out script
<?php
// If the user is logged in, delete the session vars to log them out
session_start();
if (isset($_SESSION['user_id'])) {
// Delete the session vars by clearing the $_SESSION array
$_SESSION = array();
// Delete the session cookie by setting its expiration to an hour ago (3600)
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 7600);
}
// Destroy the session
session_unset();
session_destroy();
// Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
setcookie('user_id', '', time() - 7600);
setcookie('user_email', '', time() - 7600);
setcookie('lawyer_client', '', time() - 7600);
// Redirect to the home page
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
header('Location: ' . $home_url);}
?>
I am checking to see if the session is set using this script
require_once('startsession.php');
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
So after looking at what I just put down my first guess would be that my logout script is not properly clearing my sessions...but why is it only not doing it on my shared host?
In some shared hosts you will have to include the sessions directory in order to work. Are you sure that the sessions are correctly initialized?
I have a logout script for my web app which is the following:
<?php
session_start();
require_once("config.php");
$logout_connect = mysql_connect($db_host, $db_user, $db_pass);
if (!$logout_connect){
die('Impossibile connettersi: ' . mysql_error());
}else{
mysql_select_db($db_name, $logout_connect);
mysql_query("DELETE FROM valutazioni_recenti WHERE idutente = '".$_SESSION['userid']."' ");
if(mysql_query("DELETE FROM sessions WHERE ssnid = '".$_SESSION['ssnid']."' AND userid = '".$_SESSION['userid']."'")){
$_SESSION = array();
$session_id = session_id();
session_destroy();
mysql_close($logout_connect);
header("location: login.php?logout");
exit();
}
}
?>
It makes me logout the user correctly, but, as I save session data in a DB on login and delete them on logout, I can see that if I login with a session id like "096c02aefbb34jd175bfa89d4ec1235" when I logout and login again it gives me the same sessionid to that specific user.
Is it normal? Is there a way to change it? Do I just have to mix it (or m5d it) with the login time??
you are missing something in your logout code that is your cookie values stored in user's browser . PHP function session_destroy(); doesn't delete user cookies, you have to unset them manually by setting expiry time to back date or time.
setcookie ("TestCookie", "", time() - 3600); //will set expiry time one hour back
so if you don't unset user's browser's cookie it will take same session id every time when you make new login.
This is completely normal, don't worry about it. Some other people asked about the same thing in StackOverflow.
This is due the cookies stored in your browser, so to "fix it" you must either delete the cookie either regenerate the ID with PHP.
You have a better explanation in a different post:
why is php generating the same session ids everytime in test environment (WAMP)?
Try this:
<?php
/* CREDITS: Sergio Abreu
* dosergio#gmail.com
*/
// Session Configuration
$minutes = 1 * 60; // One hour
$obsess = array();
if( $_SESSION ){
foreach ( $_SESSION as $k=>$v){
$obsess[$k] = $v;
}
session_destroy();
session_set_cookie_params( $minutes * 60);
}
ini_set( "session.use_cookies", 1);
ini_set( "session.gc_probability", 1);
ini_set( "session.gc_divisor", 1);
ini_set( "session.cookie_lifetime", $minutes * 60);
ini_set( "session.gc_maxlifetime", $minutes * 60);
//Starts new Session
session_start();
// Restore data:
if( $obsess ){
foreach ( $obsess as $k=>$v){
$_SESSION[$k] = $v;
}
}
?>
I was working on a web project which allows users to create their own sub domains dynamically.
Before creating a subdomain they should be logged in to the website.
And now was wondering how to set session variable of a user active even on the subdomains which he visits.
Tried with lot of functions like
session_set_cookie_params(0, '/', '.example.com');
**ini_set('session.cookie_domain', '.example.com' );**
but all in no wain. No function works .
So please do suggest me how to handle this.
here is my code which starts the session as soon as the user log's in:
checkusrlog.php
<?php
//for session to be active on subdomain
session_set_cookie_params(0, '/', '.xyz.com');
session_start(); // Start Session First Thing
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once "connectiontomysql.php"; // Connect to the database
$dyn_www = $_SERVER['HTTP_HOST'];
//------ CHECK IF THE USER IS LOGGED IN OR NOT AND GIVE APPROPRIATE OUTPUT -------
$logOptions = ''; // Initialize the logOptions variable that gets printed to the page
$newMessage = '';
// If the session variable and cookie variable are not set this code runs
if (!isset($_SESSION['idx'])) {
if (!isset($_COOKIE['idCookie'])) {
$logOptions = 'Register Account
|
Log In';
}
}
// If session ID is set for logged in user without cookies remember me feature set
if (isset($_SESSION['idx'])) {
$decryptedID = base64_decode($_SESSION['idx']);
$id_array = explode("p3h9xfn8sq03hs2234", $decryptedID);
$logOptions_id = $id_array[1];
} else if (isset($_COOKIE['idCookie'])) {// If id cookie is set, but no session ID is set yet, we set it below and update stuff
$decryptedID = base64_decode($_COOKIE['idCookie']);
$id_array = explode("nm2c0c4y3dn3727553", $decryptedID);
$userID = $id_array[1];
$userPass = $_COOKIE['passCookie'];
// Get their user first name to set into session var
$sql_uname = mysql_query("SELECT username, email FROM siteMembers WHERE id='$userID' AND password='$userPass' LIMIT 1");
$numRows = mysql_num_rows($sql_uname);
if ($numRows == 0) {
// Kill their cookies and send them back to homepage if they have cookie set but are not a member any longer
setcookie("idCookie", '', time()-42000, '/');
setcookie("passCookie", '', time()-42000, '/');
header("location: index.php"); // << makes the script send them to any page we set
exit();
}
while($row = mysql_fetch_array($sql_uname)){
$username = $row["username"];
$useremail = $row["email"];
}
$_SESSION['id'] = $userID; // now add the value we need to the session variable
$_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$userID");
$_SESSION['username'] = $username;
$_SESSION['useremail'] = $useremail;
$_SESSION['userpass'] = $userPass;
$logOptions_id = $userID;
?>
Note: all subdomains are managed with only single piece of code where the data which belogs to that particular subdomain is dump from database dynamically based on the subdomain.
In between am working on a shared hosting service and using *.streamicon.com as Root domain. Using *.streamicon.com as my root domain as it allows me to create 'n' number of subdomains dynamically.
Greetings,
I am working on a login system and getting stuck with Blackberry browsers authenticating. It seems they have an issue with PHP's session_regenerate_id(), can someone suggest an alternative? Here are the auth and login scripts:
UPDATE
It would appear that sessions in general are not working. Took out session_regenerate_id() just to see if it would work and it just redirects me every time, as though the $_SESSION['MD_SESS_ID']were blank. Really stuck here, any ideas would be appreciated. Cookies on the device are enabled, using a Blackberry Bold 9650. It works on my iPod Touch and every browser on my PC.
Login
<?php
session_start();
include $_SERVER['DOCUMENT_ROOT'] . '/includes/pdo_conn.inc.php';
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return $str;
}
$username = clean($_POST['username']);
$password = clean($_POST['password']);
if ($username != "" && $password != "") {
$getUser = $db->prepare("SELECT id, username, password, salt FROM uc_dev WHERE username = ? LIMIT 1");
$getUser->execute(array($username));
$userDetails = $getUser->fetch();
$dbPW = $userDetails['password'];
$dbSalt = $userDetails['salt'];
$hashedPassword = hash('sha512', $dbSalt . $password);
if ($hashedPassword == $dbPW) {
//Login Successful
session_regenerate_id();
$_SESSION['MD_SESS_ID'] = $userDetails['id'];
header('Location: http://somewhere.com');
session_write_close();
} else {
header('Location: http://www.somewhere.com');
exit();
}
} else {
header('Location: http://somewhere.com');
exit();
}
?>
Auth
<?php
//Start the session
session_start();
//Verify that MEMBER ID session is present
if(!isset($_SESSION['MD_SESS_ID']) || (trim($_SESSION['MD_SESS_ID']) == '')) {
$_SESSION = array();
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
header("Location: http://somewhere.com");
exit();
}
?>
A while ago, I was doing some Blackberry development, and found out that the browser couldn't handle multiple cookies with the same name. Not sure if they've fixed this yet.
So if you're sending out the Set-Cookie header more than once (using setcookie, session_start, or session_regenerate_id), using the same name each time, this could be causing your problem.
You might want to keep track of the cookies you need to output, in an object or array, and only send them to the browser at the very end of the request. This way, if you need to change their values in the middle of the request, you can just overwrite the array's value, rather than sending out another cookie header.
This page may also help -- someone linked to it from PHP's session_regenerate_id page.