How to unserialize codeigniter session data from database - php

I wan to use CI session in a external script and I got following data from database.
__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;
I have tried unserialize and unserialize(base64_decode($data)) but I am fail yet.
Please help to extract this data.

I got the solution here
So I have used session decode
session_decode('__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;');
So session decode stored all the encrypted data in normal php session.
Which I can access using: echo $_SESSION['ci_UserID'];
Well guys thanks for the help

If this is a session variable, you can use CodeIgniter's own session library. Consider the following code (in a controller):
$this->load->library('session'); // load the session library
$session_data = $this->session->all_userdata(); // get all session data
print_r($session_data); // print and get the corrresponding variable name, e.g. "item"
$var = $this->session->userdata('item'); // pick one that suits your needs, e.g. item
Sorry, I have read "the external script" only after having posted the code. This obviously only works in the CI framework.
For an external script you may need to have a closer look. The variables are separated by ";" and "|" and then serialized, so this might work (not tested):
$row = explode(';', '__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;'); // load the database row
$userid = explode('|', $row[1]);
$userid = unserialize($userid[1]); // now $userid holds the value "2"

Related

Is there a way to execute required php file once per session?

I am new to php and have just written a basic index.php that will display family tree information for an individual based on input id.
The index.php includes a file called "xml-people-list.php" which loads the information from the family tree and creates a sorted list of people.
My problem is that every time you click on a person to display their details, the included php is reloaded which causes the read from file and creation of sorted list to happen again.
Is there a way to only run this code once per session to avoid multiple loads?
I tried to look at session variables but wasn't sure if they would help or how to use them in this case or if there is another way?
Contents of "xml-people-list.php:
<?php require 'xml-load-person.php';
if (file_exists('people.xml'))
{
$people = simplexml_load_file('people.xml');
foreach ($people->person as $person)
{
$person_list[(string)$person['ID']] = strtoupper($person->FamilyName) . ", " . $person->GivenNames;
}
asort($person_list);
}
else
{
exit('Failed to open people.xml.');
}
?>
Thanks for any help!
Yes, you could use session variables. If you wanted to only parse the list once per visitor, and then "cache" the result into a session variable, you could do something like this (for a simple example):
if (!empty($_SESSION['person_list'])) {
// Here we fetch and decode the the ready list from a session variable, if it's defined:
$person_list = json_decode($_SESSION['person_list']);
}
// Otherwise we load it:
else {
require 'xml-load-person.php';
if (file_exists('people.xml'))
{
$people = simplexml_load_file('people.xml');
foreach ($people->person as $person)
{
$person_list[(string)$person['ID']] = strtoupper($person->FamilyName) . ", " . $person->GivenNames;
}
asort($person_list);
// Here we assign the ready list to a session variable (as a JSON string):
$person_list = json_encode($person_list);
$_SESSION['person_list'] = $person_list;
// Here we revert the JSON-encoded (originally SimpleXML) object into a stdClass object.
$person_list = json_decode($person_list);
}
else
{
exit('Failed to open people.xml.');
}
}
You will need to call session_start() in your file (either this one, or any other file including it, but importantly before any output is sent to the browser). Homework: Read up on sessions in PHP.
Update: Since SimpleXML objects can't be serialized, and since adding an object to $_SESSION causes serialization, I've updated the answer to json_encode/decode the object. Yes there's a bit of processing, but that'd be the case with the default serialization as well, and json_en/decode is fairly light-weight. Certainly heaps lighter than parsing XML on each page load!
Be aware that the returned object will be a stdClass object, not a SimpleXML object. I'm assuming it won't be a problem in your use case.
Maybe try require_once() function
1) First of all, try to see if your buttons are anchor tags then be sure that the href attribute is directing to # example: <a href="#">
2) try to use include_once instead of requiring
3) if you tried this and these couple solutions didn't work for you you can send the id of a person using the global $_GET variable
//this should be you URL http://localhost/projectname/index.php?person_id=1
// your href of each person should appoint to their URL
// <a href="index.php?person_id=1">
you can use this $_GET['person_id'] and store it into a variable so it will give you the id of person.

Custom session save_handler overwerites current saved data in database

So I finally managed to save some session data in to the database.
Now a new problem arises. When I load the page once all data is being saved.
When I reload the page and I write something to the session all data that's already in the session is being replaced with this new data. This means that with each load all the data is being replaced for new data. This is giving me problems because I'm saving a order_id into the session when there is no order_id present in the session.
This is the code that writes the data into the database. And yes it says replace into. But because this is a custom handler how can i actually append data to this current session with out renewing everything. Also how can I replace old data for new data witch is already present in the session.
The code that handles the writing to the database.
function _write($id, $data) {
$access = time();
$id = $this->session_db->real_escape_string($id);
$access = $this->session_db->real_escape_string($access);
$data = $this->session_db->real_escape_string($data);
$sql = "REPLACE INTO sessions VALUES ('$id', '$access', '$data')";
return $this->session_db->query($sql);
}
Is there something that i can do to put all the data directly after session_start() in the session variable so it always has all the data and doesn't overwrite the data with a single value when I do something like:
$_SESSION['LAST_ACTIVITY'] = time(); ?
EDIT: Also when I try to echo the session directly after the session_start();
It gives me there error
Warning: session_start(): Failed to decode session object. Session has been destroyed in /var/www/vhosts/url/httpdocs/index.php on line 13
Is there something wrong with the serialized string I don't understand why it is giving me this error.
Thanks in advance, some help will be appreciated.
Ok so now everything is working. I kinda feel embarrassed for saying what the problem was. So ok the problem and the solution.
The problem was that the session serialized data was way to long for a regular text field in the database. My string was over 500.000 characters long regular text field in database supports until 65.000+ characters.
So I changed the field from "TEXT" to "LONGTEXT" now it has enough space to save the string. And now everything works properly.
Everybody thanks for your time so far.

How to unserialize session data in a custom handler

I have used sessionHandlerInterface to save the session in database. Everything works fine. but I want to get all the serialized data from the database like
SELECT data FROM session;
and want them to decode the data when i output those.
i have tried using session_decode() which is manipulating $_SESSION array itself which is causing trouble. I just want to get the serialized data and return the decoded data.
This is the sample session data saved in database in data column
fb_422782977793963_code|s:216:"AQAVKa4Q8sOuioW75V9Ls-cDUEizgJDX5ZkRVLArDlroFvvhasdwKvbyzKEwiMVrN7nc5ghMaw0W67jQu5kt_sc_Edm9sABzB5PakdkUpXr52AViTOltPfPBQHM9T-JoGOQ4gasdbssC8Xt93NKFvdV7XRZ7ZYGZqIsu5SFpfFBHK_hNGDdRVbnbe_xUZVP9WI4h0jDy";fb_422782977793963_access_token|s:111:"AAAGAhasdaAKL7hAvXRv6FHUj1Tk24r7j4NqDwWWUzmXDZA2Igsb1pHjuP4jbBRNKfeYzutm0MFmgxuKPg1n0NEbvZAXM3bwoNZBiZCgZDZD";fb_422782977793963_user_id|s:15:"100004835469598";picture|s:61:"http://m-static.ak.fbcdn.net/rsrc.php/v2/yo/r/sdIqmHJn-SK.gif";
It works fine with normal session handling, it reads and writes session to database as it should.
I want to get all the data of active sessions. if i use SELECT data FROM sessions. it returns the above session data(encoded) i want to get the decoded data of it.
The PHP serialize and unserialize functions can not be used to serialize and unserialize session data. Even if (by default - and only by default) the serialization might look similar, there is an important difference to those two functions that care about a single variable contents only:
Those [sessions] are a list of serialized values with their variable name.
(from: Serialized README)
So you would need to create your own a session_unserialize function that is able to decode the string (e.g. via session_decode) which is returned from your database. Take care that this needs everything in there, e.g. if the session contains serialized objects, the class definitions needs to be loaded.
An exemplary session_unserialize function could look like (adopted from: a session related answer):
function unserialize_session($data) {
$hasBuffer = isset($_SESSION);
$hasBuffer && $buffer = $_SESSION;
session_decode($data);
$session = $_SESSION;
$hasBuffer ? $_SESSION = $buffer : unset($_SESSION);
return $session;
}

POST data to permanent json file using PHP

using a url, my idea is that any user can post data. For example via
http://myweb.com/index.php?name=Peter&surname=Brown
Using the "jedwards" answer, present here, I am able to create a json and save it to a file.
<?
/* This needs to be at the top of your file, without ANYTHING above it */
session_start();
/* ... */
if(!array_key_exists('entries', $_SESSION))
{
$_SESSION['entries'] = array();
}
$_SESSION['entries'][] = array("name" => $_GET["name"], "surname" => $_GET["surname"]);
$json_string = json_encode($_SESSION['entries']);
My problem is that this is not permanent amongst different session or user. It works only on the same session. On different session the json built start from the beginning.
First of all, don't use GET requests to change the state of the server. GET is only supposed to read (or.. um.. GET) data from the server.
In order to change data, use POST. It's more fitted, slightly more secure, and is great when transferring larger amounts of data.
Now, for the problem at hand. For a more permenant solution, the best option is to enforce user registration, and save the required data on a database, with a reference to the user's ID.
Yes because sessions, as the name imply, are only temporary (and sort of local). When the browser is closed it's gone. Depending on what your demands are you'll have to choose between using a database or textfiles on the server.
Cookies or sessions is not made for this kind of data.
Well if you are looking for a rudimentary solution, see below. If not, use a database as suggested in the other answers.
<?
/* This needs to be at the top of your file, without ANYTHING above it */
session_start();
/* ... */
$file = sys_get_temp_dir() . '/entries.json';
$data = file_get_contents($file);
$entries = (!empty($data)) ? json_decode($data) : array();
$entries[] = array("name" => $_GET["name"], "surname" => $_GET["surname"]);
file_put_contents($file,json_encode($entries),FILE_APPEND);

how do i reset the value of a single session array index in codeigniter?

Using a user model which returns an array that looks like this:
$user_data['display_name'] = "John Doe";
$user_data['avatar'] = ./images/user144.jpg";
i create my session using $this->session->set_userdata('user_data',$user_data);
now if on another controller i let the user change his avatar,
how can i replace the session variable associated to that?
like $this->session->set_userdata('user_data["avatar"]',$new_avatar);
just wont work right?
hee thanks for the help...
From looking at an overview of your code, I'm guessing the best way to go about this is to unset the data and reset it.
Use $this->session->unset_userdata('thesessiontounset');
Then set it back up with the new information and old.
The session->set_userdata() function will only let you modify one key at a time. In your case the key refers to an array so what you're trying to do isn't possible in the way you're attempting to do it.
When I'm updating my session I run something like this.
//Create or setup the array of the fields you want to update.
$newFields = array('avatar' = > 'image01.png');
//Check to see if the session is currently populated.
if (!is_array($this->session->userdata('abc'))){
//...and if it's not - set it to a blank array
$this->session->set_userdata('abc',array());
}
//Retrieve the existing session data
$existing_session = $this->session->userdata('abc');
//Merge the existing data with the new data
$combined_data = array_merge($this->session->userdata('abc'), $newFields);
//update the session
$this->session->set_userdata('abc',$combined_data);
More details on array_merge can be found here
First controller
$user_data['display_name'] = "John Doe";
$user_data['avatar'] = "./images/user144.jpg";
$this->session->set_userdata('user_data',$user_data);
Second controller
$user_data = $this->session->userdata('user_data');
$user_data['avatar'] = $new_avatar;
$this->session->set_userdata('user_data', $new_avatar);
It is a bit late, but it might be useful to someone else, this seems to work:
$this->session->userdata['user_data']['avatar'] = $new_avatar;
$this->session->userdata['other_data']['other'] = $other;
$this->session->sess_write();
This allows you to edit values in array just like you do with $_SESION['user_data']['avatar'] = $avatar, with 'only' one extra line and only using CI library.
For Unset Session variable
$this->session->unset_userdata('avatar');
For Set Session variable
$this->session->set_userdata('avatar', '/images/user144.jpg"');
Use just like this
$this->session->set_userdata('session_var',"");

Categories