SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    May 2006
    Posts
    426
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Can you change a cookie's value with $_COOKIE?

    It's been a while since I used cookies and I have a masic question.

    I always though you had to set a cookie with setcookie but after that you could change the value with $_COOKIE. This doesn't seem to work for me though, the value stays at what it was when I called setcookie. To illustrate this example works (cookie increments by 1 each time you refresh):

    Code:
    <?php
    
    	if( !isset( $_COOKIE[ "foo" ] ) ) {
    	
    		setcookie( "foo", "1", time() + 60 * 60 * 24 * 365 );
    		echo "Cookie not set<br />\n";
    	
    	}
    	
    	setcookie( "foo", $_COOKIE[ "foo" ] + 1, time() + 60 * 60 * 24 * 365 );
    	
    	echo $_COOKIE[ "foo" ];
    
    ?>
    Whereas this doesn't (cookie is always set to 2):

    Code:
    <?php
    
    	if( !isset( $_COOKIE[ "foo" ] ) ) {
    	
    		setcookie( "foo", "1", time() + 60 * 60 * 24 * 365 );
    		echo "Cookie not set<br />\n";
    	
    	}
    	
    	$_COOKIE[ "foo" ] ++;
    	
    	echo $_COOKIE[ "foo" ];
    
    ?>
    Is this correct? Maybe my memory is going but I don't remeber cookies working that way - can someone please confirm?

    Thanks.

  2. #2
    SitePoint Addict ruba's Avatar
    Join Date
    Apr 2005
    Location
    Amman -Jordan
    Posts
    339
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you can't work with cookie as a normal variable , you must reset the cookie with new value
    Code:
    if( !isset( $_COOKIE[ "foo" ] ) ) {
        setcookie( "foo", "1", time() + 60 * 60 * 24 * 365 );
        echo "Cookie not set<br />\n";
    } else {
       $new_val = $_COOKIE[ "foo" ] + 1;
       setcookie( "foo", $new_val , time() + 60 * 60 * 24 * 365 );
       echo $_COOKIE[ "foo" ];
    }
    Open Blocked website
    Open Blocked Website
    Knowledge Is Knowing That A Tomato Is A Fruit,
    Wisdom Is Not Putting It In A Fruit Salad.

  3. #3
    SitePoint Evangelist
    Join Date
    May 2006
    Posts
    426
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Thanks for clarifying; I think my brain has failed me.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •