2014-03-06 20 views
0

我是PHP新手,我有點被卡住了,並且很沮喪!每次用戶重新加載頁面時,我都希望這個小小的簡單網站顯示不同的圖像 - 在PHP中使用cookie。瞭解如何在PHP中首次使用cookie

我知道我的代碼是遠離正確的,但我真的很希望能收到一推在我如何能實現我的目標,朝着正確的方向

這裏是我的代碼:

<?php 
function random_image(){ 
$rdmimg = array(); 
array_push($rdmimg, "/php/rollingpin.jpg"); 
array_push($rdmimg, "/php/candlestick.jpg"); 
array_push($rdmimg, "/php/table.jpg"); 
array_push($rdmimg, "/php/table2.jpg"); 
$output = rand(0, count($rdmimg) - 1); 
echo $rdmimg[$output]; 
}; 
$a = random_image(); 
setcookie("check image", $checkimage); 

$_COOKIE = $a; 

if(isset($checkimage) 
if ($_COOKIE == $a){ 
    $i = $i + 1; 
      //I know $i isn't set, thinking of implementing somehow 
} 

?> 

<html> 
<head> 
<title>JFQ Turnings</title> 
</head> 
<body bgcolor="#ffffff" text="#000000"> 
<img src="jfqturnings.gif" alt="JFQ Turnings, coming soon." width="864" height="100"> 
<br /><img src="<?php echo $a ?>" alt="" width="864" height="567"> 
</body> 
</html> 

謝謝爲您的迴應!

+0

你應該返回'$ rdmimg [$ output];'不會回顯它。 –

+0

哦,是的,這很有道理 – webhoodlum

+0

我從來沒有設置一個cookie之前的代碼...我應該把它設置爲$ a? – webhoodlum

回答

0

看來你有在上面的代碼中使用2方法:

  1. 選擇使用$output = rand(0, count($rdmimg) - 1);陣列隨機元素。
  2. 遞增變量以跟蹤顯示哪個圖像$i = $i + 1;

我想展示兩種方法如何用嚴重評論的代碼來實現。

  1. 如果您選擇一個隨機元素,唯一的問題是確保相同的圖像不會顯示兩次。

    function random_image() { 
        $rdmimg = array(); 
        array_push($rdmimg, "/php/rollingpin.jpg"); 
        array_push($rdmimg, "/php/candlestick.jpg"); 
        array_push($rdmimg, "/php/table.jpg"); 
        array_push($rdmimg, "/php/table2.jpg"); 
        $output = $rdmimg[rand(0, count($rdmimg) - 1)]; //obtain the path of the image from the array 
        return $output; //return instead of echoing 
    } 
    
    $checkimage = random_image(); 
    
    if (isset($_COOKIE['check_image'])) //if a cookie has been set 
        while ($checkimage == $_COOKIE['check_image']) //keep attempting to get a random image that is not the current one 
         $checkimage = random_image(); 
    
    setcookie("check_image", $checkimage); 
    
    //make sure the below code is echo $checkimage NOT echo $a. 
    
  2. 相反,如果你想通過循環播放圖片,你可以試試這個方法來代替:

    <?php 
    
    $rdmimg = array(); 
    array_push($rdmimg, "/php/rollingpin.jpg"); 
    array_push($rdmimg, "/php/candlestick.jpg"); 
    array_push($rdmimg, "/php/table.jpg"); 
    array_push($rdmimg, "/php/table2.jpg"); 
    
    $count = intval($_COOKIE['check_image']); //convert to a number, strings return 0 
    $count++; //increment 
    
    if ($count < 0 || $count > count($rdmimg) - 1) //if out of range, reset 
        $count = 0; 
    
    setcookie("check_image", $count); 
    
    //make sure the code below is echo $rdmimg[$count] (replace it with the existing echo $a) 
    

這兩種方法都將返回每一次不同的圖像,但方法2將循環,而方法1只是隨機的,沒有重複。

+0

非常感謝您的回覆!他們完美地工作,我認爲你真的幫助我理解了cookie設置的基礎知識,我一直在努力 – webhoodlum