【问题标题】:PHP alter and save cookie with starting valuePHP 使用起始值更改和保存 cookie
【发布时间】:2014-08-21 17:59:47
【问题描述】:

我一直在尝试使用 cookie第一次,结果好坏参半。我希望访问者能够通过更改嵌入网址中的 1 和 0 来选择是否自动播放 youtube 视频,并将他们的选择保存在 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>

【问题讨论】:

    标签: javascript php jquery cookies youtube


    【解决方案1】:

    您可能只想在 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 值不存在”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-07
      • 2010-10-06
      • 1970-01-01
      • 2014-03-31
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多