Error — session_destroy() — Trying to destroy uninitialized session - php

I'm getting an error using session_destroy() in my PHP code.
The following script is on every page and if a user is signed in, it checks if the session is valid or not, killing the session if it's not.
session_start();
// check for users already signed in and check session
if (isset($_SESSION['user_id'])) {
$uid = $_SESSION['user_id'];
// check user_id is a valid id
if (!is_numeric($uid) || $uid < 0) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
// if user agent is different, kill session
if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
// if user's last login record fails to match session_id, kill session
$SQL = "SELECT user_session FROM users_logins ";
$SQL .= "WHERE user_id = :user_id ";
$SQL .= "ORDER BY time_in DESC LIMIT 1;";
$STH = $DBH_P->prepare($SQL);
$STH->bindParam(':user_id', $uid);
$STH->execute();
$row = $STH->fetch();
if ($STH->rowCount() > 0) {
$db_sid = $row['user_session'];
}
if ($db_sid !== session_id()) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
}
The error I receive indicates the failure is coming from the last session_destroy() call.
Am I using session_destroy() correctly or not? I have read other questions on here but most answers advise that session_start() must be used before destroying it, but I have started the session at the top, before the check begins.

You do some crazy stuff there (but you need to negotiate that with your own, I don't cover it in my answer), the reason why you see the error message is quite simple:
session_regenerate_id(true);
is commanding PHP to destroy the old session. Problem is, you already did that, one line earlier:
session_destroy();
session_regenerate_id(true);
So just take a view from above. There is no reason in an OCD manner to throw as many functions as you see fit (but actually don't understand/know well) onto your session processing. Instead take the one function that is intended to do the job and actually process it's return value if you want to put some safety net in there actually. That would be more helpful.

Related

Session variables don't update on every page

On my website, there is a function for logging in and logging out. Upon login, I set the session variables pass (which is hashed password), uid which is the ID of the user logged in and loggedIn (boolean):
$hashedpass = **hashed pass**;
$_SESSION['pass'] = $hashedpass or die("Fel 2");
$_SESSION['uid'] = $uid or die("Fel 3");
$_SESSION['loggedIn'] = true or die("Fel 4");
header("Location:indexloggedin.php");
On every page, I check if the visitor is logged in by
Checking the status of $_SESSION['loggedIn'],
Searching the database for the user with the ID $_SESSION['uid'],
Checking if the hashed password in the database matches the hashed password in the session variable:
$sespass = $_SESSION['pass'];
$sesid = $_SESSION['uid'];
$sql2 = "SELECT * FROM `users` WHERE `id` = '$sesid'";
$result2 = mysqli_query($db_conx, $sql2);
$numrows2 = mysqli_num_rows($result2);
if ($numrows2 != 1) {
$userOk = false;
}
while ($row = mysqli_fetch_array($result2,MYSQLI_ASSOC)) {
$dbpass = $row['pass'];
}
if ($sespass != $dbpass) {
$userOk = false;
} else {
$userOk = true;
}
My problem is that this seems to be working on some pages, while it doesn't work at others. For example, when I log in, I am instantly logged in to the homepage, but not to the profile page. However, after a few reloads, I am logged in to the profile page as well. The same thing happens when logging out.
For testing purposes, I tried to var_dump the password variables as well as the userOk status on the index page, and this is where I noticed something interesting. When I log out, the password variables are set to be empty, and $userOk is false, according to what that is shown at index.php?msg=loggedout. But when I remove the ?msg=loggedout (and only leave index.php), the password variables are back to their previous value, and I am no longer logged out... After a few reloads, I am once again logged out.
Why is my session variables not working as expected? It feels like as if it takes time for them to update, which is very weird. I have tried with caching disabled (both through headers and through the Cache setting in my browser).
Just tell me if you need more info.
You have initialization session_start() on every Site?
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.
After contacting my hosting provider, it was actually a hosting issue. It is now resolved!
Thanks,
Jacob

PHP - Managing Session - Doesnt Logout

I have created a user authentication system with necessary DB tables and php.
THe first time before I login (Before any SESSION is created) the redirect on every page works perfect (ie Redirects to the login page if not logged in).
But once I login with a user and then logout the same doesnt work. I think it might be a problem with not ending the SESSION (Sorry if am wrong)
Here are some pieces of the code in each Page
Login PHP
<?php
session_start();
$message="";
if(count($_POST)>0)
{
include('config.php');
echo $_POST['username'];
$result = mysql_query("SELECT * FROM members WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["id"] = $row[ID];
$_SESSION["username"] = $row[username];
$_SESSION["password"] = $row[password];
$_SESSION["mname"] = $row[mname];
$_SESSION["fname"] = $row[fname];
date_default_timezone_set("Asia/Calcutta");
$lastlog=date("d/m/Y");
$logtime=date("h:i a");
$query = "UPDATE `members` SET `lastlogin`='$lastlog',`logintime`='$logtime' WHERE `ID`='$row[ID]'";
mysql_query($query);
$_SESSION['logged'] = TRUE;
}
else
{
echo "<SCRIPT>
alert('Wrong Username/Password or Awaiting Approval');
</SCRIPT>";
header("Location:login_failed.html");
}
}
if(isset($_SESSION["id"])) {
header("Location:member/myprofile.php");
}
?>
PHP code on every page
<?php
session_start();
include('config.php');
if(!$_SESSION['logged'])
{
header("Location: ../login.html");
exit;
} ?>
And Finally Logout
<?php
session_start();
unset($_SESSION["id"]);
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["mname"]);
unset($_SESSION["fname"]);
header("Location:../login.html");
?>
Is there any problem with my Code. Am i missing something? I couldn't get it right. Pls Help
Thanks guys got it solved..
Now can you tell me How I can redirect login.php to user home page(myprofile.php) in case the User is logged in (Session exists) - Like facebook,gmail etc
Instead of calling unset() on each session var, you can simply use session_destroy(), which will destroy all of the current session data.
session_start();
session_destroy();
header("Location:../login.html");
For complete destructive power, you might also want to kill the session cookie:
setcookie(session_name(), '', 1);
See this question for a more complete example of session logout.
You need to unset $_SESSION['logged']
Also you should reference keys in the $row variable with strings. Eg $row['username'];.
Turning on E_NOTICE level warnings with error_reporting will help you with this.
If you haven't already, reset the session login
unset($_SESSION['logged']);
Or just change it to false
$_SESSION['logged'] = false;
When you are directly hitting a page in address bar for the first time then its a new request which goes to the server and server checks for existing session as written in your code. But its not same when you are pressing back button after logout. In this case there is no request is going to the server instead the request is fetched from browser cache. If you want to disable this situation then you have to tell browser explicitly to not to store your page in cache memory. For more detail please go through this link

checking session data using id, and changing id within a loop

I'm doing a little server-side project, where I need to check if a session variable is set, using session id's that are stored in my database.
The problem I'm getting, is that I don't want to destroy the session after I've checked if the variable is set. So I need a way to either check the variable without having to start the session, or find a way to change to a different session id while the session is started,
or duplicate the session to a different session that I can destroy.
Here's what I have:
while(true) {
$stmt=$db->prepare("SELECT sessionid FROM sessions");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC) {
session_id($row['sessionid']);
session_start();
if(!isset($_SESSION['value'])) {
$stmt=$db->prepare("DELETE FROM sessions WHERE sessionid=:sessionid");
$stmt->bindValue(':sessionid',$row['sessionid'],PDO::PARAM_STR);
$stmt->execute();
}
session_destroy();
}
sleep(5);
}
Done it Lol ...
while(true) {
$stmt=$db->prepare("SELECT sessionid FROM sessions");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC) {
session_id($row['sessionid']);
session_start();
session_regenerate_id(false);
$newsessionid=session_id();
session_write_close();
session_id($newsessionid);
session_start();
if(!isset($_SESSION['value'])) {
$stmt=$db->prepare("DELETE FROM sessions WHERE sessionid=:sessionid");
$stmt->bindValue(':sessionid',$row['sessionid'],PDO::PARAM_STR);
$stmt->execute();
}
session_destroy();
}
sleep(5);
}
Reference: http://uk1.php.net/manual/en/function.session-regenerate-id.php

syntax error on logout script?

I have a problem with my logout script. It works fine, if a user presses logout it kills the session and goes to logout.php where the user is told they've been logged out.
But when the browser cache is emptied or if the site should not be connected to the internet and if a user clicks the logout button it comes up with this error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
It fails beacause it cant set logout to '1' so i want to know how i might go about putting an else statement in somewhere to say redirect to logout.php so i don't get that horrible syntax error message.
Here's my code:
<?php
ob_start();
require('includes/_config/connection.php');
require('includes/functions.php');
?>
<?php
session_start();
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']."")
or die(mysql_error());
?>
<?php
// Four steps to closing a session
// (i.e. logging out)
// 1. Find the session
// 2. Unset all the session variables
$_SESSION = array();
// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Destroy the session
session_destroy();
redirect_to("login.php?logout=1");
ob_end_flush()
?>
You have double quotes and you should be using single quotes
Change this:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']."")
To:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id='" . $_SESSION['user_id'] . "'")
PLEASE NOTE You should replace all your mysql_* functions. As of PHP 5.5.0 they are deprecated. Use something like PDO or MySQLi
Yes, there is something wrong with your quotes: As long as the user_id is an integer value you could do it like this:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']);
In case it is a string, switch to single quotes:
$result = mysql_query('UPDATE ptb_users SET user_online="Offline" WHERE id="'.$_SESSION['user_id'].'"');
You can't call session_start() after output is sent- are your requires outputting anything?
Also ensure that $_SESSION['user_id'] actually has a value; print_r($_SESSION)

PHP Session Management - Basics

i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? » Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.

Categories