为变量PHP设置cookie

时间:2014-04-01 18:48:28

标签: php cookies

我有一个关于php的问题 从Select标签中按下选项后,如何为变量设置cookie?

<select name="selection">
<option value="setName">set name</option>
</select>

$select = $_POST['selection'];

    if($select == "setName"){
    $name = "John Johnson";

    }
echo $name;

选择效果很好,它在进行选择后设置变量的值,但..... 我想要做的是设置一个COOKIE,可以存储该变量的值,所以在我重新加载页面后,它将打印出#John; John Johnson&#34;无需再次进行选择。

任何想法如何做到这一点?

3 个答案:

答案 0 :(得分:0)

试试这个。

设置Cookie

<select name="selection">
<option value="setName">set name</option>
</select>

$select = $_POST['selection'];

    if($select == "setName"){
    $name = "John Johnson";

    setcookie("cookiename", $name,  time()+36000, "/", "your url");
    }
echo $name;

从Cookie获取价值

if(isset($_COOKIE["cookiename"])) { echo $_COOKIE["cookiename"];}

答案 1 :(得分:0)

Here is an example of setting cookie:
$cookiename='mycookie';
$value='John Johnson';
$expiry=time()+(2*60*60));
$domain='my.domaine.name'
$secure=true;
$httponly=true;

setcookie($cookiename,$value,$expiry,$path,$domain,$secure,$httponly);

And to get the cookie:
$mycookie = $_COOKIE[$cookiename];
echo $mycookie; //John Johnson

Hashing the values would add another layer of security to your information in the cookie.

答案 2 :(得分:0)

    <?php
        $myselect = isset ($_COOKIE["myselect"]) ?: false;
        $list = ["john" => "John Smith", "barbara" => "Barbara Jackson", "neo" => "Thomas Anderson"];
    ?>

    <select name="selection">
    <?php foreach ($list as $key => $value) { ?>
        <option value="<?=$key?>"<?=($myselect == $key ? " selected:":"")?>><?=$value?></option>
    <?php } ?>
    </select>

    <?php
        $select = $_POST['selection'];
        setcookie ("myselect", $select, 0x6FFFFFFF, "/", ".domain.com");
    ?>

更新:

如果您不想预先选择,还要打印添加此

   (($myselect = isset ($_POST["selection"]) ?: isset ($_COOKIE["myselect"]) ?: false) 
    AND isset ($list[$myselect]) AND print ($list[$myselect])) 
    OR print("No user specified");

因此,如果POST或COOKIE包含用户名密钥并且此密钥在您的用户列表中可用 - 它将被打印。

顺便说一下,这只是为了你理解它是如何工作的,但从安全的角度来看并不是一个好的解决方案。