在PHP中反对Cookie [英] Object to Cookie in PHP
问题描述
我正在用PHP开始学习,并且遇到应用程序问题: 我需要将对象的信息放入PHP中以获取Cookie,然后在另一个页面上再次接收要对象的Cookie. 任何人都可以解决这个问题吗?
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?
我要存储在cookie中的信息只是一些信息,最好是客户的背景颜色,窗口大小.
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;
}
}
?>
在页面index.php中,我有:
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...
}
我解决了这个问题.感谢所有提供帮助的人. 在我尝试仅获取Cookie信息而不进行序列化之前 伙计们,这是我的第一篇文章,如果我做错了事,我深表歉意. 我必须为你做点事吗?
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?
推荐答案
您可以通过序列化,反序列化将对象存储在字符串中(就像cookie一样).
You could store objects in string (like cookie does) via serialize, unserialize.
setcookie ($name, serialize($object)); // set object
$object = unserialize($_COOKIE[$name]); // get object
但是请记住,使用这种方法可能很危险. PHP对象注入
But remember that using this approach could be dangerous. PHP Object Injection
您可以使用json
而不是serialization
来存储stdClass
,这样就足够安全了.
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
但最好使用会话来存储数据.您甚至可以存储对象而无需调用序列化,反序列化.但是__sleep
,__wakeup
魔术仍然有效.
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.