Roblog

Image Rotation in PHP

Have a lot of images that you want to rotate on each page refresh? Here’s your solution.

I wrote this because it’s always getting bleedin’ asked in HG&P, and the code in the General Discussion sticky is horrid. However, you don’t have to be a member of OcUK to enjoy randomly-generated imagey goodness.

Directions

  1. Create a new directory on your server, and upload the images you’d like in your rotation to that directory.

  2. Open Notepad, or your favourite text editor.

  3. Paste the following code:

    $files = glob('{*.PNG,*.png,*.JPG,*.jpg,*.GIF,*.gif}', GLOB_BRACE);
    readfile($files[array_rand($files)]);
  4. Save the file as rotate.php, and upload it to the directory that you just uploaded your images to.

    Make sure it has a .php extension, and not .php.txt.

  5. Edit your signature on the forums, and paste the link to your rotate.php between image tags, an example being:

    [img]http://yourdomain.com/sigs/rotate.php[/img]
    
  6. Optional step: Some forums block .php extensions on images (phpBB does this by default, I believe). If you run the Apache webserver with mod_rewrite installed (there’s a 90% chance that you do), you can use this little trick to fool the software into thinking your image is a regular one.

    1. Open Notepad or your favourite text editor.

    2. Paste the following code:

      RewriteEngine On
      RewriteRule ^.*$ rotate.php
      
    3. Save the file as .htaccess and upload it to the same directory as your images are in. If you’re using Notepad, it might complain that this is an invalid filename; if you have this problem, you can usually just use your FTP client to rename the file to .htaccess.

    4. Use the following as your image link, obviously replacing yourdomain.com/sigs/ with the correct URL:

      [img]http://yourdomain.com/sigs/rotate.png[/img]
      
  7. All done! Enjoy.

And here’s an example of what it looks like in action:

Randomly generated image with quotes