Question

I am new to PHP and would like to know how to setup and use Cookies to store user menu selections between pages.

Basically, when a user say clicks on a menu option called "About Us", I would like to somehow store this selection via a cookie that I could then use somewhere else?

FYI, I am using the jquery .click function to determine which menu option is selected, i.e.

        $("ul.sf-menu li a").click(function() {
        var menu_opt = $(this).attr("href");
    });

Thanks.

Was it helpful?

Solution

First of all you need setcookie

<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);
?>

and then you need to retrieve it using:

   echo $_COOKIE['TestCookie'];

To set a classdepending on cookie:

<a href="about"  <?php if($_COOKIE['TestCookie'] === "About"){ echo "class='selected'";}?>>About page</a>

The idea hereis to check the value of our cookie and ifits what we want then weecho the class assignation. There are much better ways of achievingwhat you want without the use of cookies.

If this is not what you want you will have to reword that question much better because as it is I am taking guesses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top