I am starting my studies in PHP and I'm having problems with an application:
I need to put information of an object in PHP for a cookie and then receive a cookie to object again on another page.
anyone has any solution to this problem?
The information I want to store in cookie is just some information preferably Customer as background color, size of windows.
<?php
class Client {
private $id;
private $pSize;
private $color;
function __construct($id) {
$this->id = $id;
}
public function getPSize() {
return $this->pSize;
}
public function setPSize($pSize) {
$this->pSize = $pSize;
}
public function getColor() {
return $this->color;
}
public function setColor($color) {
$this->color = $color;
}
}
?>
In a page index.php i have:
<?php
include_once 'Client.class.php';
//Test Preference Client
$client = new Client(1);
$client->setColor("#000000");
$client->setPSize(200);
//using Serialize to put to Cookie
$StringClient = serialize($client);
//Store to Cookie
$_COOKIE['PreferenceClient'] = $StringClient;
?>
In a another page i get the inrofmation:
if(isset($_COOKIE['PreferenceClient'])){
// Unsing Unserialize to Object
$objClient = unserialize($_COOKIE['PreferenceClient']);
//Test data:
echo $objClient->getColor();
//Continue with Performing changes to the client if the information exists...
}
I solved the problem. Thanks to everyone who helped.
before i had tried only get the cookie information without serialize
Guys, this is my first post, I apologize if I did something wrong.
I have to make something up for you?
You could store objects in string (like cookie does) via serialize, unserialize.
setcookie ($name, serialize($object)); // set object
$object = unserialize($_COOKIE[$name]); // get object
But remember that using this approach could be dangerous. PHP Object Injection
You could use json instead of serialization to store stdClass, it would be safe enough.
setcookie ($name, json_encode($object)); // set object stdClass
$object = json_decode($_COOKIE[$name]); // get object stdClass
But it's prefer to use session to store your data. You could even store object without calling serialize, unserialize. But __sleep, __wakeup magic still works.
setcookie, $_COOKIE, serialize, magic with serialization.
The answer is: You don't.
Whenever you take data from the client and use it in your code,
you have to implement security that prevents the case when the user changes his client data and injects something unexpected into your server. The client is easily able to fake and change cookie data, and thus to change your object.
Example:
If we serialize the object from Alma Do's answer and store the values in a cookie, the client/user could see our database auth settings from
public function __sleep() {
return array('server', 'username', 'password', 'db');
}
The client now can change his cookie to use a fake server instead of your server, fake your login / user table and pretend to be admin.
I think this is a case of XY Problem, please let us know what exactly is your goal.
This sounds more then a session function. You shouldn't transfer data over a Cookie. In Cookies you only save short information like a session token or a hash or some settings. To transfer and hold data the PHP session function is much better.
http://www.php.net/manual/de/book.session.php
In your session you can serialize some data if you want or save only an array or a value.
session_start(); // on every page
$_SESSION['test'] = "123123";
echo $_SESSION['test'];
to send serialized object you must use a specified thing like time() to bypass SPAM and control the timeOut!
session_start();
setcookie('myobject',serialize("Myvalue"),(time()+(3600*24*30)));
be sure to get stored on the session :
unset($_SESSION['myobject']);
Store your object
$_SESSION['myobject'] = unserialize($_COOKIE['myobject']);
Restore your Obecjt :
$mySeriaLizedObject = $_SESSION['myobject'];
Related
I Know A PHPSESSID in the server how can i read a session variable that is set to a PHPSESSID ( i don't want to use $_SESSION because i don't want start session in this thread ) i only want read session data with using PHPSESSID ??
PHP :
<?php
namespace MyApp;
class readSession extends \Thread {
private $sess_id,$data_name;
public function __construct($SESSID,$data_name){
$this->sess_id = $SESSID;
$this->data_name = $data_name;
}
public function run(){
$data = $this->readSession($this->sess_id,$this->data_name);
}
private function readSession($SESSID,$data_name){
session_id($SESSID);
session_start();
$temp = $_SESSION[$data_name];
var_dump($_SESSION);
session_destroy();
return $temp;
}
}
i write this code to read users session's data but it remove the users session data
First of all, reading another user's session data is a horrible idea. If you need to have shared access to that data - don't store it in the session.
Secondly, reading another doing it via session_start() with the same session ID is an even worse idea - that way you are effectively acting as that user. There's no easy/reliable way to read session data without intercepting it, but that's not by accident, it's exactly because you shouldn't do it.
That being said, don't call session_destroy() and the user's data won't be removed ... destroy means destroy. If you're looking for a way to just close a session, that's session_write_close().
I make use of session_set_save_handler(). It works fine. However, sometimes I need to alter user's session data. I simply expected that the session data passed to write function are internally created like this:
serialize($_SESSION);
But they are not. They have this slightly different format than simple PHP serialized data:
user|a:24:{s:2:"id";s:2:"12";s:5:"email";s:19:...CUT...;}last_activity_time|i:1310535031;logged_everywhere|b:1;
Anybody knows what kind of serialization is internally used for serializing $_SESSION data for write function in session_set_save_handler() ? Or even better, if there is some unserialize and serialize function I can use to work with this data ?
Please take a look at the PHP-Dokumentation for session_decode and session_encode. You will find complete samples for unserializing and serializing session strings in the comments.
here's my 2 cents on this issue with php's internal serializer. it's not really parse-able outside of the user's session. So when I used session_set_save_handler() so I can save my session data to a database, and inside my write method, I can access the $_SESSION object, thus, I can save the serialized $_SESSION object to my database, then read or alter it there. The only drawback is, that if it's altered, it wont be a modification to the internal session data used by php.
This at least gives you parse-able access to the current user's session data, although, not the object.
function _write($id, $data)
{
if ($data == "")
{
return true;
}
global $database_connection;
global $table_prefix;
$clean_data = base64_encode(serialize($_SESSION));
$access = time();
$id = mysql_real_escape_string($id);
$access = mysql_real_escape_string($access);
$data = base64_encode($data);
$sql = "REPLACE
INTO " . $table_prefix . "sessions
VALUES ('$id', '$access', '$data', '$clean_data')";
return mysql_query($sql, $database_connection);
}
I have recently gone into extending my site using node.js and have come to realisation I need a session handler for my PHP sessions. Now everything was cool and dandy and node.js reads the php sessions and can propogate it's own session with the php ones. I am using database sessions so the session data gets saved into a field in the database.
I have however found a slight problem. I am attempting to read the session data into node.js and it's really quite a strange string. I have been able to get the strucutre of each session variable down to:
'field_name'|'type':'length':'value';
Now on certain strings the value field can be missing on other strings the length can be missing (when a variable is Null). The type can also be more than b, s, i; it can also be N (NULL).
I had originally thought up of a huge translator for JS but this just somehow seems a very wrong way to do it.
Has anyone here tried to extract php session variables in JS before and is there any kind of script that could help? Maybe there is a formatting thing I can use on PHP side to make my life a lot easier in node.js?
Edit: the Schema looks like:
{ _id: { id: 'L:\u00c1\u009d\u008e\u00ad\u000e}<\u0002\u0000\u0000' }
, session_id: 'a2clfnjhopv1srs5k5elgbfjv5'
, user_id: 0
, session_data: 'logged|b:0;uid|i:0;server_key|N;AUTH_TIER2|b:0;email|s:0:"";cheese|s:6:"cheese";'
, active: 1
, expires: 1278920567
}
This is the mongo db record for a user session. The field needing to be translated is session_data. There is some kind of formatting error when pasting it in since stackoverflow wont format that as code when I try and make it for some reason.
I tried to JSONfy the field before but it lost it's types and didn't read Null entries etc so I stopped that
Thanks,
I'm relatively sure PHP uses the serialize and unserialize functions to handle session data.
There is a JavaScript implementation of unserialize in PHP.JS, you can find it here: http://phpjs.org/functions/unserialize
Here is a session_decode function based on the unserialize function of phpjs:
https://github.com/vianneyb/phpjs/blob/master/functions/var/session_decode.js
works for me!
Just to reply with the way I've found: force PHP to use JSON instead :
Use the class below, with session_set_save_handler to store data as JSON and let PHP still using his own system.
Link this class using this function at the beginning of each script you use session :
http://php.net/manual/ru/function.session-set-save-handler.php
PS : here the class use memcache to store JSON resulting object, on Node.JS, use a memcache object, and retrieve like this :
get the PHPSESSID from cookies
use that characters string to bring a key from memcached with "sessions/id" where id is the key and session just the string (see class below).
Now you should have only JSON in memcache, so it's becoming a simple game with Node.JS to work with.
PS : of course you can work with/improve this, you can also use this not only with memcache (a db for example)
<?php
/**
* This class is used to store session data with memcache, it store in json the session to be used more easily in Node.JS
*/
class memcacheSessionHandler{
private static $lifetime = 0;
private static $memcache = null;
public function __construct(){
self::$memcache = new Memcache();
self::$memcache->addServer('localhost', 11211);
}
public function __destruct(){
session_write_close();
self::$memcache->close();
self::$memcache = null;
}
public static function open(){
self::$lifetime = ini_get('session.gc_maxlifetime');
return true;
}
public static function read($id){
$tmp = $_SESSION;
$_SESSION = json_decode(self::$memcache->get("sessions/{$id}"), true);
$new_data = session_encode();
$_SESSION = $tmp;
return $new_data;
}
public static function write($id, $data){
$tmp = $_SESSION;
session_decode($data);
$new_data = $_SESSION;
$_SESSION = $tmp;
return self::$memcache->set("sessions/{$id}", json_encode($new_data), 0, self::$lifetime);
}
public static function destroy($id){
return self::$memcache->delete("sessions/{$id}");
}
public static function gc(){
return true;
}
public static function close(){
return true;
}
}
?>
I had the same problem. I needed to integrate php with node.js. I used js-php-unserialize to do this. The use is pretty straightforward.
var PHPUnserialize = require('php-unserialize');
console.log(PHPUnserialize.unserializeSession(yourData));
For example if you
var yourData = 'A|s:1:"B";userID|s:24:"53d620475e746b37648b4567";';
you will get this result:
{
A: 'B',
userID: '53d620475e746b37648b4567'
}
I was hoping someone could help me with a question I've come up on.
I have a Session object that handles storage of general session data, I also have a Authentication object which validates a users credentials.
Initially I passed the desired Authentication class name to my Session object then had a login method that created an instance of the Authentication object and validate the credentials. I stored the result of this validation in a Session variable and made it available via a getter. The user data was also stored in the Session for later use. In addition to all this, I have a logout method, which removes the user data from the Session and thus logging the user out.
My question is what role should the Session object play in users logging into their account?
And what other ways might one suggest I go about handling user login, as it stands right now I feel as though I'm getting too much wrapped up in my Session object.
Simply calling your authenticate method should trigger logic within Auth to store the proper data in the session (or some other data store) and Auth should also be used exclusively to retreive/revoke this info. So using the example form your comment it might be:
class Auth {
public static function authenticate($identity, $pass)
{
// do lookup to match identity/pass if its good then
/* assume $auth is an array with the username/email or
whatever data you need to store as part of authentication */
Session::set('auth', $auth);
return true;
// if auth failed then
Session::set('auth', array('user'=>'anonymous'));
return false;
}
public function isAuthenticated()
{
$auth = Session::get('auth');
if(!$auth)
{
return false;
}
return (isset($auth['user']) && $auth['user'] !== 'anonymous');
}
}
[...] as it stands right now I feel as
though I'm getting too much wrapped up
in my Session object.
And id agree. Idelaly for authentication/credentials you shoudl only be interacting with the Auth/Acl object(s). They would then utilize the session as stateful store... but you shouldnt care that its even stored in session. The code utilizng the Auth/Acl object(s) should be completely unaware of this fact.
For example:
//Bad
if($session->get('authenticated', 'auth'))
{
// do stuff
}
// also bad
if(isset($_SESSION['authenticated']))
{
// do stuff
}
//Good
if($auth->isAuthenticated())
{
// do stuff
}
// inside $auth class it might look like this
public function isAuthenticated()
{
$store = $this->getSotrage(); // assume this returns the $_SESSION['auth']
return isset($store['authenticated']);
}
The session is a good place for holding user data that you want to have managed in some sort of state across various pages or if you need a fast accessible way to get at it without hitting the database. It is a bad idea to keep secure information (re: passwords/etc) in the session, but rapid access information like username, name, email address, preferences, etc is all good data to put in the session. Try to keep it simple though.
Keep in mind though, that the session (or related cookie) should only ever be used for identification. It should not be used for authentication.
Authentication object is a good method. Make sure that it only holds secure information as long as it needs to and that it has all the necessary functions available to keep sensitive data protected.
I have instantiated a class in my index.php file. But then I use jQuery Ajax to call some PHP files, but they can't use my object that I created in the index.php file.
How can I make it work? Because I donĀ“t want to create new objects, because the one I created holds all the property values I want to use.
Use the session to save the object for the next page load.
// Create a new object
$object = new stdClass();
$object->value = 'something';
$object->other_value = 'something else';
// Start the session
session_start();
// Save the object in the user's session
$_SESSION['object'] = $object;
Then in the next page that loads from AJAX
// Start the session saved from last time
session_start();
// Get the object out
$object = $_SESSION['object'];
// Prints "something"
print $object->value;
By using the PHP sessions you can save data across many pages for a certain user. For example, maybe each user has a shopping cart object that contains a list of items they want to buy. Since you are storing that data in THAT USERS session only - each user can have their own shopping cart object that is saved on each page!
Another option if you dont want to use sessions is to serialize your object and send it through a $_POST value in your AJAX call. Not the most elegant way to do it, but a good alternative if you don't want to use sessions.
See Object Serialization in the documentation for more informations.
mm, you should store in session, $_SESSION["someobj"] = $myobj;, and ensure that when you call the Ajax PHP file this includes the class necessary files which defines the class of $myobj and any contained object in it.
Could you be more specific? I can try.
This is how I create an object then assign it to a session variable:
include(whateverfilethathastheclassorincludeit.php)
$theObject = new TheObjectClass();
//do something with the object or not
$_SESSION['myobject'] = $theObject;
This is how I access the object's members in my Ajax call PHP file:
include(whateverfilethathastheclassorincludeit.php)
$theObject = $_SESSION['myobject'];
//do something with the object
If you don't want to move your object that is in your index.php, have your ajax make a request to index.php but add some extra parameters (post/get) that let your index.php know to process it as an ajax request and not return your normal web page html output.
You have not provided code, but what I guess is that you need to make your instantiated object global for other scripts to see it, example:
$myobject = new myobject();
Now I want to use this object elsewhere, probably under some function or class, or any place where it is not getting recognized, so I will make this global with the global keyword and it will be available there as well:
global $myobject;
Once you have the object, you can put it into the session and then utilize it in the Ajax script file.
As others have suggested, $_SESSION is the standard way to do it, in fact, that was one of the reasons, that sessions where invented to solve. Other options, i.e. serializing the object rely on the client side to hold the object and then return it untampered. Depending on the data in the object, it is not a good solution, as a) the object may include information that should not be available on the client side for security reasons and b) you will have to verify the object after receiving it.
That said, and if you still want to use the object on the client side, then JSON is an option for serializing object data, see JSON functions in PHP.
Based on most of the answers here, referring to storing the object in $_SESSION, is it more efficient to store only the individual properties that need to be accessed in AJAX as opposed to the whole object, or does it not matter?
E.g.
$_SESSION['object'] = $object;
vs
$_SESSION['property1'] = $object->property1;
$_SESSION['property2'] = $object->property2;
I know the OP is asking about accessing the entire object, but I guess my question pertains to if it's just a matter of only accessing certain properties of an object, and not needing to access methods of a class to alter the object once it's in AJAX.