2015-10-31 78 views
1

我有下面的代碼不幸的是它不工作。我收到通知未定義索引:imagerotate。我無法解決這個問題。有人能幫助我嗎?謝謝。Cookie - 通知:未定義

<?php 
$imgArray = array("header_1000x150_basnenaprani_3_o.png", "header_1000x150_basnenaprani_1_m.png", "header_1000x150_basnenaprani_1-zlatá.png"); 
// Path to where your images are stored 
$hostDir = "http://myweb.com/wp-content/uploads/2015/10/"; // Don't forget that ending '/' 

$imgArraySize = count($imgArray); // Store the size of the array (starts at 1) 
$imgToShow = 0; // We'll default to always show the first image. 

// Check to see if the cookie has already been created. 
if ($_COOKIE['imagerotate'] != "") { 
    // The cookie existed 
    $imgToShow = $_COOKIE['imagerotate']; 
    if($imgToShow + 1 >= $imgArraySize) { 
    // The image we were supposed to show next would have been out of bounds in the array. 
    $imgToShow = 0; // We'll show the first image 
    } 
    else // The image to be shown is not out of bounds. 
    $imgToShow++; // Increment the image counter 
} 

// Write the new cookie with the new image we are showing 
setcookie ("imagerotate", $imgToShow, time()+5); 

//Print the image from the directory. 
echo "<img src=\"".$hostDir.$imgArray[$imgToShow]."\" alt=\"An Image\" />"; 

?> 
+0

如果cookie已被設置,您是否再次設置cookie? – Andrew

回答

0

嘗試這個辦法:用 「isset」 的if語句(上phptester.net測試):

<?php 
    $imgArray = array("header_1000x150_basnenaprani_3_o.png","header_1000x150_basnenaprani_1_m.png", "header_1000x150_basnenaprani_1-zlatá.png"); 
    // Path to where your images are stored 
    $hostDir = "http://myweb.com/wp-content/uploads/2015/10/"; // Don't forget that ending '/' 

    $imgArraySize = count($imgArray); // Store the size of the array (starts at 1) 
    $imgToShow = 0; // We'll default to always show the first image. 

    // Check to see if the cookie has already been created. 
    if (isset($_COOKIE['imagerotate']) != "") { 
    // The cookie existed 
    $imgToShow = $_COOKIE['imagerotate']; 
    if($imgToShow + 1 >= $imgArraySize) { 
    // The image we were supposed to show next would have been out of bounds in the array. 
    $imgToShow = 0; // We'll show the first image 
    } 
    else // The image to be shown is not out of bounds. 
    $imgToShow++; // Increment the image counter 
    } 

// Write the new cookie with the new image we are showing 
setcookie ("imagerotate", $imgToShow, time()+5); 

//Print the image from the directory. 
echo '<img src="'.$hostDir.$imgArray[$imgToShow].'" alt="An Image" />'; 

而且,改變這一行:

echo "<img src=\"".$hostDir.$imgArray[$imgToShow]."\" alt=\"An Image\" />"; 

這樣:

echo '<img src="'.$hostDir.$imgArray[$imgToShow].'" alt="An Image" />'; 
+0

謝謝!不幸的是,刷新後圖像改變。所以setcookie中的5秒仍然不起作用。 –