点击按钮

时间:2017-01-06 15:24:26

标签: php post cookies setcookie

我制作了一个小网页,您可以通过单击按钮来设置cookie的值。奇怪的是,当我点击按钮时他并没有改变价值,但是当我再次点击同一个按钮而不是它的工作时,我必须按下按钮上的2以获得新值

有人知道我做错了吗?

<?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 个答案:

答案 0 :(得分:1)

Cookie值不会在自己的请求周期中设置,如果设置它,重定向/刷新后值将正确显示。

编辑:

在设置cookie后添加了一个刷新的工作示例。 (可以使用一些清理,但它只是为了说明在cookie中设置数据的工作方式)

<?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>

答案 1 :(得分:0)

你必须首先启动一个PHP会话,并且你的变量命名样式是错误的,这是一个工作正常的修正版本。

<?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>
相关问题