我有一个网站,我想随机选择页面的背景图片。此图像应保存在会话变量中,直到浏览器关闭。在每次页面刷新时,一次又一次地调用随机函数,但它应该保留在会话中。那么如何将背景图像保存到浏览器会话中,使用drupal或者通常是php,直到浏览器关闭为止?
这里每个页面调用的代码加载随机函数。
<div id="page" style="background: url('/sites/all/themes/klickers/css/images/bgtop-0<?php echo rand(1, 4); ?>.jpg') no-repeat 50% 0 #000000;" class="<?php print $classes; ?>">
答案 0 :(得分:1)
<?php
session_start(); //call this before doing anything else
if (isset($_SESSION['bgimage'])) {
$bgimage = $_SESSION['bgimage'];
}
else {
$bgimage = mt_rand(1,4); //mt_rand() is the better rand()
$_SESSION['bgimage'] = $bgimage;
}
?>
<!DOCTYPE HTML>
...
<div id="page" style="background: url('/sites/all/themes/klickers/css/images/bgtop-0<?php echo $bgimage ?>.jpg') no-repeat 50% 0 #000000;" class="<?php print $classes; ?>">
答案 1 :(得分:1)
像这样的东西会这样做
<?php
session_set_cookie_params(0); // this will ensure your session destroys when browser is closed
session_start();
if(!isset($_SESSION['bgImage'])) {
$bgImage = rand(1, 4);
$_SESSION['bgImage'] = $bgImage;
}
?>
<div id="page" style="background: url('/sites/all/themes/klickers/css/images/bgtop-0<?php echo $_SESSION['bgImage']; ?>.jpg') no-repeat 50% 0 #000000;" class="<?php print $classes; ?>">
<强> EDITED 强>
添加session_set_cookie_params(0);