Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object to Cookie in PHP

Tags:

php

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?

like image 609
Fabrício Rosal Avatar asked Nov 20 '13 13:11

Fabrício Rosal


Video Answer


1 Answers

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.

like image 165
sectus Avatar answered Sep 20 '22 18:09

sectus