开发者

How do I save any string in the users browser? is this useful?

I know that through cookies or something like that you can save things in the user's PC/browser. It would be useful for me to save the users location after he typed it, so I can adjust开发者_如何学C all the info accordingly. My question is, what is the best way to do that and how long is the info saved? And finally if I wanted to save for example the word "pizza" and access it later how do I do it?

Thanks. I know it's a lot and all very noobish.


A simple example:

page1.php

<?php
  setcookie('favorite_food', 'pizza');
?>
I just set your favorite food to "pizza". <a href="page2.php">Want to see?</a>

page2.php

Your favorite food is <?php echo $_COOKIE['favorite_food'] ?>.

The function for setting is setcookie. You provide a name for the cookie, the value (contents), when it should expire (time() + $number_of_seconds_until_it_should_expire), and then some other options regarding where on your site this cookie can be accessed. If you give no expire time, most browsers will delete the cookie once the browser is closed. The PHP setcookie documentation is much more detailed and is a good starting point for any more specific questions you may have.

It can later be accessed via $_COOKIE['name_you_used_when_setting'].

A general note: always remember that, when dealing with cookies, you can't trust the user not to change them or delete them at any time. Use them only for convenience, and never for something like setcookie('user_is_admin', 1) or setcookie('user_is_banned', 1).


Save it in a cookie. It's saved for as long as you specify, unless the user clears their cookies. As for setting it, take a look at PHP's setcookie() function

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜