问题
My page loads a random background image every time it loads:
<?php
$input = array(1, 2, 3, 4, 5, 6, 7, 8);
$num = array_rand($input, 1);
$bg = "img/bg" . $num . ".jpg";
?>
But I want it to do that only once. I want the image to remain the same after a visitor submits a form, for example, thereby reloading the page.
I've tried if($bg=NULL) etc, but to no avail - I guess $bg becomes null again every time the page reloads.
Many thanks in advance!
回答1:
You can use Session variable or cookies if is not set, you choose a background, if is set, you do nothing
回答2:
Got it (thanks to Ricardo):
<?php
session_start();
if (!isset($_SESSION['num'])) {
$input = array(1, 2, 3, 4, 5, 6, 7, 8);
$_SESSION['num'] = array_rand($input, 1);
}
$bg = "img/bg" . $_SESSION['num'] . ".jpg";
?>
来源:https://stackoverflow.com/questions/14429795/choose-random-value-only-once