2012-02-07 49 views
1

我试图在用户每次刷新页面时显示随机横幅。我面临的问题是我不想再次显示最后的横幅。我有没有其他的方式来记住最后显示的一个,而不使用cookie或数据库实现?记住上次显示的横幅

Cookie实施:

<?php 

$randIndex = rand(1,6); 
if(!isset($_COOKIE["lastDispalyed"])){ 
    setcookie("lastDispalyed",$randIndex,time()+60*60*24); 
} 
else{  
    while($_COOKIE["lastDispalyed"] == $randIndex){ 
     $randIndex = rand(1,6); 
    } 
    setcookie("lastDispalyed",$randIndex,time()+60*60*24); 
} ?> 

<img src="images/mainBanners/<?php echo $randIndex; ?>.JPG"/>

+0

你可以使用'$ _SESSIONS'。为什么你不想让他们看到另一个广告,也如果你只有六个,你可能会用尽广告 – Cjueden 2012-02-07 18:50:33

回答

2

你可以使用一个会话变量:

<?php 

    session_start(); // <-- start session before outputting any HTML 

    $randIndex = rand(1,6); 

    if (!isset($_SESSION["lastDisplayed"])) { 

     $_SESSION["lastDisplayed"] = $randIndex; 

    } else {  

     while ($_SESSION["lastDisplayed"] == $randIndex) { 
      $randIndex = rand(1,6); 
     } 

     $_SESSION["lastDisplayed"] = $randIndex; 
    } 

?> 

参考session_start()

+0

我得到无限循环错误与此代码... – 2012-10-22 20:46:37

+0

@DarrylHebbes它说什么? – paislee 2012-10-22 23:40:53

+0

它显示一个超时消息,实际上是我的错误。 如果rand(1,1)发生,则while循环旋出。 所以不用担心,你的例子很好。 – 2012-10-24 11:09:11

0

设置为旗帜的ID或URL会话变量:

$_SESSION['lastDisplayed'] = $id; //could be the id of the banner you are displaying, or the file's url, whatever you have access too 

然后测试它,当你去显示一个新的旗帜。