How to add / edit a cookie in php?

孤人 提交于 2019-12-06 15:46:17
GWW

One thing that you should consider using is serialize and unserialize to encode your cookie data. Just be careful though, from my experience you have to use stripslashes on the cookie value before you unserialize it. This way you can unserialize the data, change the values, reserialize the cookie and send it again. Serialize will make it easier in the future if you want to store more complex data types.

for example:

setcookie("mycookies",serialize($cookies_array),time()+60*60*24*30);

// This won't work until the next page reload, because $_COOKIE['mycookies']
// Will not be set until the headers are sent    
$cookie_data = unserialize(stripslashes($_COOKIE['mycookies']));
$cookie_data['foo'] = 'bar';
setcookie("mycookies",serialize($cookies_array),time()+60*60*24*30);

I would store just an id in the cookie and use a flat file (ini, serialized or plain text) or database to store the values. The thing is - cookie are severely space-limited and you should add as little as possible. One one of my latest projects i had to store alot of information and, since i had access to ssd drives, i put the arrays and objects serialized in zipped files and in the cookies i saved the id, and then some hashes of varios parts of the data to be able to do some quick validation.

And, from a security point of view, having just an id (and a hash of the local data so one can't easily change the id or some other form of verification of that id) is more secure than putting the data in the cookie.

Do you have any special reason to save data as cookies?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!