Programming Wiki: Misc. Web Programming

Programming Wiki : PHPandJavascriptCookies

WikiHomePage :: Categories :: PageIndex :: RecentChanges :: RecentlyCommented :: Login/Register

Misc. Web Programming

Setting and Reading Cookies in PHP and Javascript

This is very easy. My goal was to set a cookie from some javascript and read the cookie in php and take action. The is to determine if a menu on the page has been collapased previously and if so display it as collapased when the new page opens.

In javascript setting is as simple as this:
document.cookie = "menu_state=closed";
document.cookie = "menu_state=open";

These will set a variable "menu_state" to either the vaule open or closed.

To determine what the javascript has set the variable to in php do this:
if ($_COOKIE['menu_state'] == 'closed')
      //Closed menu
      echo "<script language='javascript' type='text/javascript'>";
      echo "menuColap('main');";
      echo "</script>";
} else {
    //This seems unnecessary??  but anyways, its an example  of setting a cookie in php
    $_COOKIE['menu_state'] = 'open';
    //open menu
    $main_menu_html ='';
    $fh = fopen('./menu.html','r') or die($php_errormsg);
    while (! feof($fh)) {
              $main_menu_html .= fread($fh,1048576);
    echo $main_menu_html;

The only important part is the if statement and the $_COOKIE array.

There are no comments on this page. [Add comment]

Powered by Wikka Wakka Wiki
Page was generated in 0.0223 seconds