简体   繁体   中英

What is the best way to store cookie information?

I need to store information about shopping products added to buy. I'm thinking to create a cookie with a encrypted value that will be stored in a database along with data associated with that cookie, and based on client cookie to retrieve information from database. No Login, No Session.

You can simply create cookie as

$name='john';
$value=1;
setcookie($name,$value,time() + (86400 * 30));

and then You can create a database 'cookie_db' and can insert these cookies simply as

$query='insert into cookie_db values($name,$_COOKIE[$name'])';

hope it helps!!

Sessions are definitely the way to go. The only way the session gets destroyed is if the user closes the browser or the expiry time exceeds. Which is configurable through php.ini.

Try this

// Start a session
session_start();

// Add values to the session
$_SESSION["cart_items"] = array("item 1", "item 2");

Now the session var should be accessible after calling session_start() from page to page.

Session will automatically add a cookie, and will retrieve the data as needed.

See this: http://php.net/manual/en/function.session-start.php

And this: http://php.net/manual/en/reserved.variables.session.php

setcookie("cookie_name","cookie_value", time() + (86400 * 30), "/");

or you can set cookie with jquery

<script type="text/javascript">
function setCookie(cname, cvalue, exdays)
{
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
setCookie('cookie_name','data_of_cookie');
</script>

i hope this will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM