Does session_set_save_handler method will lose the session data? - php

How can I get the session data when use session_set_save_handler?
When I refreshed the page, all the session data lost if i use the session_set_save_handler. however,if i delete the session_set_save_handler, all is right!
There is the code
<?php
/*
Session open (called by session_start( ))
Session close (called at page end)
Session read (called after session_start( ) )
Session write (called when session data is to be written)
Session destroy (called by session_destroy( ) )
Session garbage collect (called randomly)
*/
function sess_open($sess_path, $sess_name) {
//print "Session opened.\n";
//print "Sess_path: $sess_path\n";
//print "Sess_name: $sess_name\n\n";
return true;
}
function sess_close( ) {
//print "Session closed.\n";
return true;
}
function sess_read($sess_id) {
//print "Session read.\n";
//print "Sess_ID: $sess_id\n";
return '';
}
function sess_write($sess_id, $data) {
//print "Session value written.\n";
//print "Sess_ID: $sess_id\n";
//print "Data: $data\n\n";
return true;
}
function sess_destroy($sess_id) {
//print "Session destroy called.\n";
return true;
}
function sess_gc($sess_maxlifetime) {
//print "Session garbage collection called.\n";
//print "Sess_maxlifetime: $sess_maxlifetime\n";
return true;
}
session_set_save_handler('sess_open','sess_close','sess_read','sess_write','sess_destroy','sess_gc');
session_register_shutdown('session_write_close');
session_start();
if(isset($_SESSION['foo']))
$_SESSION['foo'] = "have the foo data";
else $_SESSION['foo'] = "no foo data";
echo $_SESSION['foo'];
?>
It always output 'no foo data',when I refresh the page.
if I delete the
session_set_save_handler('sess_open','sess_close','sess_read','sess_write','sess_destroy','sess_gc');
session_register_shutdown('session_write_close');
it always output 'have the foo data'.
Who can tell me why? Very thanks!

Related

Session loses variable stored after parent.location.reload() called in PHP

Below is the main code that goes to the session and constructor after it stores data in the session.
if(!$result->uid) {
$this->member_model->scripts("Wrong ID or PWD.");
} else {
$userdata['uid'] = $result->uid;
$this->session->set_userdata($userdata);
//header('location: /adminBase.php');
echo "<script>";
echo "parent.location.reload();";
echo "</script>";
exit();
}
On the login part, it stores UID through $this->session->set_userdata($userdata);,
Here is the part where it stores
public function set_userdata($data, $value = NULL)
{
if (is_array($data))
{
foreach ($data as $key => &$value)
{
$_SESSION[$key] = $value;
}
return;
}
$_SESSION[$data] = $value;
}
but when it goes to the constructor through
echo "<script>";
echo "parent.location.reload();";
echo "</script>";
it removes previous session that keeps UID.
if ($class instanceof SessionHandlerInterface)
{
if (is_php('5.4'))
{
session_set_save_handler($class, TRUE);
}
else
{
session_set_save_handler(
array($class, 'open'),
array($class, 'close'),
array($class, 'read'),
array($class, 'write'),
array($class, 'destroy'),
array($class, 'gc')
);
register_shutdown_function('session_write_close');
}
}
else
{
log_message('error', "Session: Driver '".$this->_driver."' doesn't implement SessionHandlerInterface. Aborting.");
return;
}
// Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers
if (isset($_COOKIE[$this->_config['cookie_name']])
&& (
! is_string($_COOKIE[$this->_config['cookie_name']])
OR ! preg_match('/^[0-9a-f]{40}$/', $_COOKIE[$this->_config['cookie_name']])
)
)
{
unset($_COOKIE[$this->_config['cookie_name']]);
}
session_start();
// Is session ID auto-regeneration configured? (ignoring ajax requests)
if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) OR strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest')
&& ($regenerate_time = config_item('sess_time_to_update')) > 0
)
{
if ( ! isset($_SESSION['__ci_last_regenerate']))
{
$_SESSION['__ci_last_regenerate'] = time();
}
elseif ($_SESSION['__ci_last_regenerate'] < (time() - $regenerate_time))
{
$this->sess_regenerate((bool) config_item('sess_regenerate_destroy'));
}
}
// Another work-around ... PHP doesn't seem to send the session cookie
// unless it is being currently created or regenerated
elseif (isset($_COOKIE[$this->_config['cookie_name']]) && $_COOKIE[$this->_config['cookie_name']] === session_id())
{
setcookie(
$this->_config['cookie_name'],
session_id(),
(empty($this->_config['cookie_lifetime']) ? 0 : time() + $this->_config['cookie_lifetime']),
$this->_config['cookie_path'],
$this->_config['cookie_domain'],
$this->_config['cookie_secure'],
TRUE
);
}
$this->_ci_init_vars();
log_message('info', "Session: Class initialized using '".$this->_driver."' driver.");
Above is the part of the Session.php file. I tried to add session_start(); on every function in the else statement as well as set_userdata function as people gave a solution but it didn't work. Session.php gets called from the construct file as below and then it makes a new session, which doesn't have UID. How would I be able to keep UID from the login part..?
public function __construct() {
parent::__construct();
$this->load->library('session'); --> this calls Session.php file
$this->load->model('member_model');
$this->load->model('setting_model');
$this->load->helper('iny_common_helper');
$this->load->helper('url');
if($this->session->userdata('uid')) {
$this->memberInfo = $this->member_model->get_member_infoByUid($this->session->userdata('uid'));
}
if($this->memberInfo->no) {
$this->member_model->memberInfo = $this->memberInfo;
}
I think you are under a slight confusion.
parent.location.reload() is a javascript construct that trigger the reload of the parent of the current window. In your case, it will trigger the reload of the login page, because you are not in an iframe embedded in a parent page, you are in a page, you have no parent.
You need to replace the code below with a redirect to the page that redirected to the login page (or the current home)
echo "<script>";
echo "parent.location.reload();";
echo "</script>";
You can use php or javascript.
php:
header('Location: https://example.com/');
javascript:
echo "<script>";
window.location.replace("https://example.com/");
echo "</script>";
I would use php :), in your case the else branch would become:
} else {
$userdata['uid'] = $result->uid;
$this->session->set_userdata($userdata);
header('Location: https://example.com/');
exit;
}
Do not forget tu replace the example.com with your correct url.
The exit (or die()) statement is important, should be present, also the header() function only works if it is the first output (no echo's, print's, etc before), otherwise you will need to use the javascript redirect.

user-defined function for unsetting session is not working

I want a simple function where give a session it just echo it and then unset it. I have written something i have written this:
function sess_caller($sess){
if(isset($sess)){
echo $sess;
}
unset($sess);
}
It does echo the session but doesn't unset it afterwards.
function killSession($key="")
{
if($key!="" && isset($_SESSION[$key]))
{
unset($_SESSION[$key]); //this will empty the key value pair from the
$_SESSION (global) variable in php.
}
else{
//if not needed session anymore just destroy it.
session_destroy();
}
}

jquery & php + if session is dead an error is returned

I've noticed if the session is dead (on an Jquery AJAX PHP Request) the data returned is preceeded with an error message if the session is needed in the request.
How do other sites deal with this?
Similar code is shown below - eg: its using a SESSION variable in the code which doesn't exist as the session is dead.
public function internal($variable) {
if($_SESSION['data'] == $variable) {
echo TRUE;
}else{
echo FALSE;
}
}
Should I use isset to check if the variable exists?
Should I be coding for dead sessions?
thx
You need to add the isset also:
public function internal($variable) {
if(isset($_SESSION['data']) && $_SESSION['data'] == $variable) { //add here
echo TRUE;
}else{
echo FALSE;
}
}
Try this
public function internal($variable) {
if($_SESSION['data']!="" && $_SESSION['data'] == $variable) { //add here
echo TRUE;
}else{
echo FALSE;
}
}
You can also do like this,
public function internal($variable) {
if(!empty($_SESSION['data']) && $_SESSION['data'] == $variable) { // modify here
echo TRUE;
}else{
echo FALSE;
}
}

Carrying a value stored in a session from one page to another

I was watching a lesson on lynda.com and the code works for them but will not work when I try it. This is the exact code they use. Could use some help to why it is not working.
<?php
class Session
{
public $message;
function __construct(){
session_start();
$this->check_message();
}
public function get_message($msg="") {
if(!empty($msg)) {
// then this is "set message"
$_SESSION['message'] = $msg;
} else {
// then this is "get message"
return $this->message;
}
}
private function check_message() {
// Is there a message stored in the session?
if(isset($_SESSION['message'])) {
// Add it as an attribute and erase the stored version
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
?>
and on the calling page
<?php
require_once("session_class.php");
function output_message($msg="") {
if (!empty($msg)) {
return "<p>$msg</p>";
} else {
return "";
}
}
if (isset($_SESSION['message'])) {
echo "session is set";
} else {
echo "session is not set";
}
$message = $session->get_message("working");
//$message = "Working";THIS WILL WORK
echo output_message($message);
?>
You haven't created an object instance on the calling page. Try this:
require_once("session_class.php");
$session = new Session();
EDIT
When you take out check_message() from the __construct, the SESSION is set because in your check_message() method, you have this:
unset($_SESSION['message']);
It basically destroys your session, that's why you see that message "session is not set".
If you want the session to be set, simply delete that line.

cakephp session can't be written

Controller
function login() {
// Don't show the error message if no data has been submitted.
$this->set('error', false);
// Does not render the view
$this->autoRender = false;
// If a user has submitted form data:
if(!empty($this->data)) {
$someone = $this->Student->findByStudentEmail($this->data['Student']['email']);
if(!empty($someone['Student']['student_pwd']) && $someone['Student']['student_pwd'] == $this->data['Student']['password']) {
$this->Session->write('eyeColor', 'Green');
$this->Session->write('Student', $someone['Student']);
// session information to remember this user as 'logged-in'.
echo "success";
} else {
echo "failed";
}
}
function main(){
$this->set('students', $this->Student->find('all'));
$this->set('eyeColor', $this->Session->read('eyeColor'));
// Render the specified view
$this->render('/pages/main');
}
view
main.ctp
<?php print $eyeColor; ?>
<?php echo $session->read('eyeColor') ?>
It's in the manual: http://book.cakephp.org/view/1466/Methods
Admittedly, though, it's not very clear. Maybe I'll submit an update.

Categories