Site logo

Archived topic

Rotating background

4 replies · Started by Hans on July 26, 2019

Viewing posts 1–5 of 5

I want to change the background on specific pages/articles of my site. Therfore I use this php:

<?php
/*
By Matt Mullenweg > http://photomatt.net
Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
Latest version always at:
http://photomatt.net/scripts/randomimage
*/// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';

// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';

$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';

$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along

header('Location: '.$folder.$files[$rand]+'?'+(new Date()).toString();); // Voila!
?>

On the specific pages/articles I use this hook (after header content):

<img src='http://swimages.spd-simmerath.de/bgimage/rotate.php' id='ktgbild' alt=''>

With Edge it works fine. With Firefox only when I refresh the page. Opera and Chrome always show the same background.

I change the .htaccess as follows:

# BEGIN WordPress
<filesMatch "\.(html|htm|php|jpg)$">
 FileETag None
 <ifModule mod_headers.c>
 Header unset ETag
 Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
 Header set Pragma "no-cache"
 Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Nothing changes in the behaviour. The network protocol doesn't show any access to the background file.

What is wrong with my site? The URL shown below should have a changing background. With legacy hoohs it works on another site.

-

That code looks pretty complicated.

I would just do something like this in the hook:

<?php
$images = array(
    'https://yoursite.com/img1.jpg', 
    'https://yoursite.com/img2.jpg', 
    'https://yoursite.com/img3.jpg'
);

$random_image = array_rand( $images );
?>

<img src="<?php echo $images[ $random_image ]; ?>" />

Your code works. The only disadvantes is that I have to modify it when I delete or add images.

Thanks!

That's true, but it does simplify the code considerably. I'm not very good with the folder lookup kind of PHP, unfortunately.

This archived topic is closed to new replies.