PHP修改和保存cookie的起始值

PHP alter and save cookie with starting value

本文关键字:cookie 修改 保存 PHP      更新时间:2023-09-26

我第一次尝试使用cookie ,结果喜忧参半。我希望访问者能够选择如果youtube视频自动播放或不通过改变1和0在嵌入url,他们的选择保存在一个cookie,当他们返回。在第一次访问视频应该自动播放。我认为我的问题可能是不知道如何设置新的值到cookie正确?

目前,我正在努力保留值,当访问者查看页面后和/或首先设置值。只要在URL中保留?autoplay=0以防止自动播放,该网站几乎可以像预期的那样工作。

我需要保存最后一次选择的自动播放状态在一个cookie中,这样访问者就不需要每次返回时都重新选择它。

理想的(但不是必要的)解决方案是不需要?autoplay=0,除非访问者点击链接进行切换(不知道这是容易还是复杂的实现-但在我看来cookie可能使url变量无用?)。

index . php

<?php
// This might be very unneccessary,
// should probably look at the cookie and not the url?
// Can't figure out how though.
if($_GET['autoplay'] == "0"){ 
$autoplay = "0"; 
}else{ 
$autoplay = "1"; 
}
setcookie("autoplay",$autoplay, time()+3600*24);
$_COOKIE['autoplay'] = $autoplay;
?>
<!DOCTYPE html>
<html>
<body>
        <button class="randomizerButton" data-href="data.php">Randomize</button>
        <hr>
        <div id="results">
        <?php include('data.php'); ?>
        </div>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $('button.randomizerButton').click(function(){
                    scriptUrl = $(this).attr('data-href');
                    $.post(scriptUrl, function(response){
                        $('#results').html(response);
                    });
                });
            });
        </script>
</body>
</html>

data.php

<?php
$var = array(  
    array("Hello", "0wLljngvrpw", "10", "15"),   
    array("Hey", "TINASKjjNfw", "20", "25"),  
    array("Right in the dick! I shot you friend right in the di... Potatoes, Potatoes.", "rzU_fLcxIN0", "30", "35"),
);  
// array_rand returns the INDEX to the randomly 
// chosen value, use that to access the array. 
$finalVar = $var[array_rand($var)];  

echo('<iframe id="ytplayer" width="557" height="315" 
src="http://www.youtube.com/v/'.$finalVar[1].'&start='.$finalVar[2].'&end='.$finalVar[3].'&autoplay='.$_COOKIE["autoplay"].'" 
frameborder="0"></iframe>');
?>
<a href="?autoplay=1">Autoplay 1</a>
&nbsp;|&nbsp;
<a href="?autoplay=0">Autoplay 0</a>
<br><br>

您可能希望仅在url参数存在时才设置cookie(当其中一个链接被单击时)。检查参数是否设置:

<?php
if (isset($_GET['autoplay']) || !isset($_COOKIE['autoplay'])) {
    if($_GET['autoplay'] == "0"){ 
        $autoplay = "0"; 
    } 
    else{ 
        $autoplay = "1"; 
    }
    setcookie("autoplay",$autoplay, time()+3600*24);
    $_COOKIE['autoplay'] = $autoplay;
}
?>

|| ! isset ($_COOKIE['autoplay'])是因为您想要1作为默认值,如果用户从未选择任何。它的意思是"如果cookie值不存在"