下面的代码将首先显示链接A,然后显示链接B。
cookie被保存在用户PC上,如果用户一次又一次刷新,他将寻找不同的链接,但是如果他单击并离开而其他用户单击并离开页面,该怎么办呢?根据此代码,用户始终会看到第一个链接第一次点击。
如果我使用会话而不是cookie怎么办?会话将保存在服务器上,并且两个链接将由不同的用户分发。还是给我这种逻辑的替代方案?
if(!isset($_COOKIE["lastLink"])){
setcookie("lastLink","b"); // you can set an expire time.
}
if($_COOKIE["lastLink"] == "a"){
$link = "www.b.com";
setcookie("lastLink","b");
}elseif($_COOKIE["lastLink"] == "b"){
$link = "www.a.com";
setcookie("lastLink","a");
}
echo $link;
DIKKKAT!不建议使用MySQL,请改用MySQLi。
如果使用数据库存储链接,则可以使用以下方法:
(我没有尝试,因为我没有数据库表,请尝试并反馈给我)
<?php
$resource = mysql_query($query); // mysql query
$i = 0; // loop value
$links = array(); // links container
while( $values = mysql_fetch_array($resource) )
{
$links[$i] = $values["link_column"];
$i++;
}
// What if it is users first visit?
if(!isset($_COOKIE["lastLink"])){
// we dont know how many links will be in the DB. also, be aware that indexes start with zero.
setcookie("lastLink",count($links));
}
$cookie = $_COOKIE["lastLink"]; // I'm a lazy programmer, sorry
// we pass the value of cookie and the array of links here, bcz it can be a problem.
echo gimme_the_link($cookie,$links);
// Iterate the cookie value to the next link
$cookie = ($cookie!=count($links)) ? $cookie+1 : 0;
setcookie("lastLink",$cookie);
function gimme_the_link($cookie,$links){
$return = ($cookie!=count($links)) ? $links[$cookie+1] : $links[0];
return $return;
}
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句