dopt85756 2014-08-21 00:20
浏览 36
已采纳

使用session(或cookie)存储PHP变量?

I've been looking into using a variable to let visitors choose if embedded Youtube videos autoplay or not. I've been thinking about using a link like myurl.com/?autoplay=0 to stop autoplay and 1 to enable it again. I read a bit about sessions (don't know if that's the best practice here though since I'm new to PHP), but couldn't quite get it to work after loading a second video. If anyone could point out my error(s) and help me, or suggest a better way to solve it, I'd be most grateful.

index.php

<?php
session_start();
$_SESSION['autoplay']=0
?>

<!-- content here removed for readability -->
        <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>

data.php

if ($_SESSION['autoplay'] == "0"){
    $autoplayVar = 0;
}
else{
    $autoplayVar = 1;
    }

echo ($autoplayVar);

echo ('<br>');


echo('<iframe id="ytplayer" width="557" height="315" src="http://www.youtube.com/v/0wLljngvrpw&autoplay='.$autoplayVar.'" frameborder="0"></iframe>');
  • 写回答

2条回答 默认 最新

  • douhuang5623 2014-08-21 00:29
    关注

    I'd look at it like a shopping cart, when you add items to your basket you want them to be saved even if you close the browser, or come back after a while.

    Cookies are Similar to Session Variables ** in PHP, **the only difference that sets both apart is that Sessions are handled and saved in the Server (Usually being used to test Login State)

    While Cookies are saved in the Client's Browser (Usually for less important stuff like preferences). look at cookies! Cookies by PHP

    Cookies let you save some NON-Important data. You can set the Auto-Play, or the Background-Theme, (Even the remember me? Done with Cookies!) with cookies.

    setcookie("autoplay", $value);
    

    And to get back the data :

    $Does_he_want_autoplay = $_COOKIE['autoplay'];
    

    You can find all and more in the link I gave.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题