PHP rotating image link

Not sure if this is the best way to do this - probably not - but here's one way to have some links that rotate on refresh so that one is an image link and the others are text links. I hope this helps someone.

First, here it is. (Refresh the page a couple of times and you'll see).

Great, eh?

So, for the rotation, we first need to read and set a cookie. One of the values of the cookie will be based on how many links we have, so we need to put our links up here too. For the links, we can use an array of arrays - like this:

PHP
$links=array(
array('wine.jpg',"http://wine.com","WINE"), // image, link, alt/link text
array('whisky.jpg',"http://whisky.com","WHISKY"),
array('beer.jpg',"http://beer.com","BEER")
);

Then, we read the cookie if it's already been set to see which value to give the new cookie. (I hope this makes sense).

PHP
if ($rotate==count($links)-1) { // '$rotate' is the name of the cookie
$which=0; // if the cookie's there and it's reached the end - go back to 0
}
else {
$which=$rotate+1; // go to the next one. If the cookie's not set, it's '1'.
}
setcookie ('rotate', $which, time()+31536000, '/', 'bonrouge.com', '0');

Putting these together, we put this at the top of the page - before any html.

PHP
<?php
$links=array(
array('wine.jpg',"http://wine.com","WINE"), // image, link, alt/link text
array('whisky.jpg',"http://whisky.com","WHISKY"),
array('beer.jpg',"http://beer.com","BEER")
);
if ($rotate==count($links)-1) { // '$rotate' is the name of the cookie
$which=0; // if the cookies there and it's reached the end - go back to 0
}
else {
$which=$rotate+1; // go to the next one. If the cookie's not set, it's '1'.
}
setcookie ('rotate', $which, time()+31536000, '/', 'bonrouge.com', '0');
?>

Then, in the html, where we want the image (and other links) to go, we can put this...

PHP
<ul id="rotate-img-link">
<?php
$image=$links[$which]; // this says which image to show
echo '
<li class="image"><a href="'.$image[1].'"><img src="'.$image[0].'" height="50" width="50" alt="'.$image[2].'" /></a></li>';
$i = 0;
while ($i < count($links)) {
if ($i<>$which) {
echo '
<li><a href="'.$links[$i][1].'">'.$links[$i][2].'</a></li>'; //links
}
$i++;
}
?>
</ul>

The CSS for this page is like this:

CSS
/** rotate-img-link **/
#rotate-img-link {
list-style:none;
margin:10px auto;
width:10em;
border:1px solid gray;
}
#rotate-img-link a:link {
color:gray;
}
#rotate-img-link a:hover {
color:red;
}
#rotate-img-link a img {
border:0;
display:block;
}
#rotate-img-link .image {
float:left;
padding:0 10px;
}

And that's it.

Comments

#1
2008-09-27 Melissa says :

Your+site+is+very+interesting+and+useful

#2
2009-03-27 Rush says :

Nice site... Cool guestbook...l

Comment form

Please type the word 'forum' here:

BB code available :

  • [b]...[/b] : bold
  • [it]...[/it] : italic
  • [q]...[/q] : quote
  • [c]...[/c] : code
  • [url=...]...[/url] : url