Change value cookie by clicking button

2.3k views Asked by At

I made a litte webpage were you can set the value of a cookie by clicking on a button. The strange thing is that when i click on the button he didn't change the value but when i click again on the same button than it's work i have to push to 2 on the button to get the new value.

Does anybody know what i do wrong ?

<?php
if(isset($_POST['On'])) 
{ 
    setcookie("Test", "On", time()+3600, "/","", 0);
    $Result=$_COOKIE['Test'];
}
else if(isset($_POST['Off'])) 
{
    setcookie("Test", "Off", time()+3600, "/","", 0);
    $Result=$_COOKIE['Test'];
}
else{}
?>
 <form id="Test" action='' method='post'>
  <button type='submit' name='On'>ON</button>
  <button type='submit' name='Off'>OFF</button>
</form>
<p><?= $Result;?></p>
2

There are 2 answers

0
Robert On

Cookie values do not get set in their own request cycle, if you set it the value will display correctly after a redirect/refresh.


Edit:

Added working example with a refresh after setting the cookie. (Could use some cleanup, but it's just to illustrate the workings of setting data in cookies)

<?php

    if (isset($_POST['On']))  { 

        setcookie("Test", "On", time()+3600, "/","", 0);
        // refresh current page
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;

    } else if (isset($_POST['Off'])) {

        setcookie("Test", "Off", time()+3600, "/","", 0);
        // refresh current page
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }

    // always try and fetch cookie value
    $Result = isset($_COOKIE['Test']) ? $_COOKIE['Test'] : 'no cookies here...';

?>

<form id="Test" action='' method='post'>
  <button type='submit' name='On'>ON</button>
  <button type='submit' name='Off'>OFF</button>
</form>
<p>Cookie value: <?= $Result;?></p>
2
Francis Sunday On

You have to start a PHP session first, and your variable naming style is wrong here's a corrected version that works fine.

<?php

session_start();

if(isset($_POST['On'])) 
{ 
    setcookie("Test", "On", time()+3600, "/","", 0);

    $result = $_COOKIE['Test'];
}
else if(isset($_POST['Off'])) 
{
    setcookie("Test", "Off", time()+3600, "/","", 0);

    $result = $_COOKIE['Test'];
}

else 
{
    $result = null;

}
?>
 <form id="Test" action='' method='post'>
  <button type='submit' name='On'>ON</button>
  <button type='submit' name='Off'>OFF</button>
</form>
<p><?= $result;?></p>