Im having problems with session variable after my database have changed the session variable, it doesnt update the new session variable when i press the back button but on database, it already updated but not on the webpage, i have to relogin to see the new variable.
and how do i use session_regenerate_id?
Copied from php.net:
<?php
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
?>
When a user presses the back button, their browser generally shows a cached page, rather than re-requesting the page, so that's most likely where your issue is coming from.
You use session_regenerate_id by calling it... and the user will be given a new session ID and their session will be transfered over to that ID, if you pass True as a parameter, the session will be cleared, too. It's generally used to prevent session fixation attacks
Make sure that you have put below statement on top of your script otherwise no sessions will be handled:
session_start();
Related
I'm trying to destroy the session without using session_destroy because I want to carry the information message. My question is if my code is valid, I already reset the session by saying all $_SESSION is an empty array or for security reason using the session_destroy is a must but if I use session_destoy I can't pass the $_SESSION['msg'] anymore.
<?
session_start();
$_SESSION = array();
//session_destoy();
$_SESSION['msg'] = "You have logged out.";
header('Location: index.php');
?>
You need session_unset()
session_unset just clears out the session for usage. The session is
still on the users computer. Note that by using session_unset, the
variable still exists. session_unset just remove all session
variables. it does not destroy the session....so the session would
still be active.
via: http://php.net/manual/en/function.session-unset.php
and then you can do it like
$_SESSION['msg'] = "You have logged out.";
so that the msg is added to session.
OR You can do it like this too:
$msg ="Whatever the message is";
header("Location: index.php?message=$msg ");
In index.php file
if(isset($_GET['message']) && !empty($_GET['message'])){
echo $_GET['message'];
}
1st you should use session_unset(); to remove all session variables/values rather than assigning a new array to it.
The main answer to your query:
I would recommend to use session_destroy() because it removes the internal session ID generated which would be validated at every request coming from a client device. To verify this, just print the session ID using the function echo session_id(); before and after emptying the session in the way you are doing. It would pring the same session ID.
So destroying it first and then creating new will be a good idea.
Once you destroy the session using session_destroy() you can start a new session again and set your message $_SESSION['msg'] in it.
Just user session_unset($_SESSION['session_name']); hope this will work.
You can use cookies; you would keep for example the username, the password and the connection status of the user. When the user comes back to your site, you know who he is and if he is already connected.
setcookie ("Msg", "you have logged out", time () + 3600);
(for a cookie of one hour, you put the time that you want ...)
Your code:
<?
session_start();
$_SESSION = array();
//session_destoy();
$_SESSION['msg'] = "You have logged out.";
header('Location: index.php');
?>
in the index page do below stuff:
<?php
if(!empty($_SESSION['msg']) && isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
this will show your message once and unset it immediately.
i have searched and searched and read and read a lot about what exactly session_destroy does ! but no result at least for me ! first read the details below :
When a session is created (session_start) a file is created with a
unique identifier that is given to the user as a cookie, when
variables in the $_SESSION array are modified or added the temporary
file is updated with that information so that it can be used somewhere
else on the website.*
session_destroy* will delete this file, this is commonly done for when
a user logs out of your website so that the (now useless and
unnecessary) file isn't taking up space.
we know that session id is stored in session cookie and as the tutorials say , session destroy removes the session cookie file (that includes session_id ) so why when i started a new session it didn't generate a new id ! it makes me confused ! look at the example :
<?php
session_start();
echo session_id();
session_destroy();
session_start();
echo "---".session_id();
?>
result : l4k80dkrl5kd6cdlobhbu5s3i1---l4k80dkrl5kd6cdlobhbu5s3i1
so it gives me the session id same as the previous one .
so what does session_destroy really do !! ?
thanks in advance
From PHP documentation:
It does not unset any of the global variables associated with the
session, or unset the session cookie.
So after session_destroy() the cookie that holds the session id is still alive, and just the session file will be deleted. So start_session() tries to find the file for the session id in the cookie, and it fails of course, and it just creates a new empty file for that. So your id does not change.
If you really want to change that, try to delete the cookie.
You are almost correct about what you have said, BUT if you destroy the session and the script ends in PHP, thats the time file is deleted. If you just try to destroy and create it again, it uses the same file/session ID.
Its not only the file that is created, but also the file contains all the data you are storing in the session. Have a look at your session data in your server, its very interesting.
Update
More interesting things you can do. Write a PHP file
<?php
session_start();
sleep(29000);//delete the session after 29 seconds
session_destroy();
?>
Now have a look at the session file, it should be deleted after 20 seconds.
Do
<?php session_start(); ?>
and go to google chrome, and remove the cookie manually from there. The session won't be available anymore.
<?php session_destroy(); ?> will not destroy the cookies on the
client side. Next time you create a session, it will just use the same
old information. This is the prime reason of your question.
Do
file1:
<?php session_start(); $_SESSION['test'] = "A"; ?>
file2:
<?php session_start(); $_SESSION['test'] = "B"; ?>
resultFile:
<?php session_start(); echo $_SESSION['test']; ?>
Now from two computers, access your website with file1 on one computer and file2 on another. From google chrome, switch their cookie information and see how session A is assigned to B and B is assigned to A.
I have implemented session into my application, but I need to allow the logged in user to use the back button to go to the previous pages.
How do I make sure that the session does not expire and allows the user to view the previous page?
Here is my code
<?php
//Start session
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
$User = $_SESSION["User"];
//Page content
?>
I have started the session, when I use the back button on browser I get a page that reads session has expired. Which I do not want to happen.
in your php at the top of each page, start your session before your opening <html> tag
<?php session_start(); ?>
<html>
in your php somewhere set your session variables note this value must be serializable
<?php $_SESSION["variable"] = "value"; ?>
then anytime you want to access that session variable you can do the following AFTER calling session_start();
<?php echo $_SESSION["variable"]; ?>
if you handle your sessions in this manner, session variables will be available on previous and future pages.
caveat:
depending on browser and headers sent from your server, when you go back a page, it reloads the page as it was in the cache so consider the following:
User goes to page and is does not have a session variable set
User does action that sets a session variable and sends them to a second page
User hits back button
User is shown the pre-session cached version of the first page
User refreshes page
User now sees the first page w/ session variable set
the reason for the hiccup is that some browsers do not always make a new request on back button sometimes it loads from the browser cache. read the very end of this answer: https://stackoverflow.com/a/1313941/884453
EDIT
You posted code above with a check to session_status first. This is incorrect. You ALWAYS need so session_start();
<?php
//Start session
session_start();
// User is either pulled from the session or is null
$User = $_SESSION["User"] ? !empty($_SESSION["User"]) : NULL;
//Page content
?>
the code for if (session_status() !== PHP_SESSION_ACTIVE) { is only useful in situations where some other bit of code (usually in a framework) may have started the session already.
If you have set up your session management correctly, you don't need to do anything.
However, this correctly depends on what kind of state you have in the session and how you manage it. Also timeouts will still apply (as they should).
You can use javascript history method also for that so your session also remain same.
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script>
I'm having a difficult time with PHP doing some very basic session security type of things:
A new session ID should be generated when switching from a non-authenticated context to an authenticated one
A new session ID should be generated when switching from an authenticated context to a non-authenticated one
What I'd like to do is not only regenerate a session ID when switching contexts, but also immediately put something into the session (such as a FLASH) when switching those contexts. These three pages should hopefully clarify my expectations:
<?php
/* page1.php */
session_start();
# Just putting something in the session which I expect to
# not show up later
$_SESSION['INFO1'] = 'INFO1';
?>
<html>
Page 2
<?php print_r($_SESSION) ?>
</html>
So when this page is displayed, I expect to see INFO1 show up. I also expect when I come back here NOT to see INFO2 show up. If I don't already have a session ID, I expect to get one (I do).
<?php
# page2.php
session_destroy();
session_regenerate_id(TRUE);
$_SESSION['INFO2'] = 'From page 2';
session_write_close();
header('Location: page3.php');
exit;
?>
This would be most akin to a logout function - we invalidate the existing session by passing TRUE to session_regenerate_id. Also, I put something in the (presumably) new session - which may be like a FLASH - say "You've been logged out successfully.
#page3.php
<html>
<body>
<?php session_start(); ?>
<?php print_r($_SESSION); ?>
</body>
</html>
On this page, I'd expect two things to happen:
The redirect from page2.php should have sent me a new session ID cookie (it did not)
I'd expect for the print_r to print information from INFO2, and not from INFO1. It doesn't have information from INFO1, but does not include information from INFO2.
I've had very, very inconsistent results with session_regenerate_id and redirects. It seems like such a kludge to manually send that Set-Cookie header - but even if I didn't, session_regenerate_id(TRUE) should invalidate the old session ID anyhow - so even if the browser didn't for some reason get the new session ID, it wouldn't see any information in the session because the old session had been invalidated.
Has anybody else had experience with these sorts of issues? Is there a good way to work around these issues?
Based on the documentation for session_regenerate_id, it sounds like the contents of the session are always preserved. You're passing it a TRUE argument, but that only deletes the actual session file on disk; the values stored in it are kept in $_SESSION and then written to the new session.
So perhaps wipe it out manually:
$_SESSION = array();
Not sure why you aren't seeing the new cookie, though. Where did you check, what did you see?
edit: The problem, as revealed by the OP in a comment below, appears to be that page2 never called session_start to load the first session. Which produces the following:
<?php
session_start(); # Load the old session
session_destroy(); # Nuke it
session_unset(); # Delete its contents
session_start(); # Create a new session
session_regenerate_id(TRUE); # Ensure it has a new id
$_SESSION['FLASH'] = "You've been logged out";
session_write_close(); # Convince it to write
header('Location: index.php');
?>
I have no idea if this is minimal. Figuring out how much of it can be deleted is left as an exercise to the reader.
I have this query in mysql in a php page:
mysql_query("INSERT INTO tz_todo SET text='".$text."',
position = ".$position.",
user_id=".$_SESSION['user_id'].",
view_stat=0");
I tried to echo the query and the result is this:
INSERT INTO tz_todo SET text='trial text', position = 21, user_id=, view_stat=0
it seems that it can't get the session value of user_id.
And $_SESSION['user_id'] is not working in social engine. How to correct this? I also made a localhost version in my xampp and everything is fine but when I converted it into social engine, session is not working.
In any page where you are using session objects, place this code at the beginning of the file:
if(!isset($_SESSION)){session_start();}
This way if the session is not already started, it starts it; otherwise it ignores the session start if the sesion is already started.
This is important because calling session_start() if session is started already can sometimes cause errors.
That's how I get my user id through session
session_start();
$userID = $viewer->getIdentity();
$_SESSION['user_id'] = $userID;
echo $_SESSION['user_id'];
Using session to store the user_id is totally wrong. To gain a user_id try
$viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity(); (or $user->getIdentity if you have another user's object).
If you still need to use session for storing this data, use Zend-approach.
session_start();
$_SESSION["test"] = "hello world";
session_start();
echo $_SESSION["test"];
does above code work ? if not, check your session.save_path in the php.ini
NOTE: to retain this variable remember to call session_start() on each php script/page before calling for the variable from the session.
Yoy might be forget to start your session at the top of the page
<?php if(!isset($_SESSION)){ session_start(); } ?>
$_SESSION['user_id'] might not stored a value. check your login page (Basically after login session variables will set) or after register weather you assigned a value to that session variable..
setting a value to a session variable :
$_SESSION['user_id'] = "1234567";