In the web forums I participate in, I have an avatar that changes randomly.
Since I’ve been asked several times about this, I thought I’d explain how I do it, so anyone can make a random avatar for themselves.
Some people thought my avatar(s) is an image stored on my web site and that it changes every 10 minutes or so. That’s not what happens. A random image is actually selected every time the avatar is loaded. And using PHP and Apache it’s really simple, too.
The only problem with this technique is that some (all?) forum software makes all avatars have the same size you specify on your preferences, which means that you should make all the images the same size, so they won’t be distorted when displayed.
- Select a few images you’d like to have as an avatar.
- Resize them all to the same dimensions.
- Open a text editor, copy the following PHP code into a new file and save it as
avatar.jpg:
1<?php
2$dh = opendir(".");
3while (false !== ($file = readdir($dh))) {
4 if ($file != ".htaccess" && $file != "avatar.jpg" && $file != "." && $file != "..") {
5 $filelist[] = $file;
6 }
7}
8
9srand((double)microtime() * 1000000);
10$picnum = rand(0, sizeof($filelist) - 1);
11header("Location: " . $filelist[$picnum]);
12closedir($dh);
- Create another text file with the following content and name it
.htaccess:
1<files avatar.jpg>
2 ForceType application/x-httpd-php
3</files>
- Place all the files in a directory on your web site.
- Configure your forum avatar(s) to point to the
avatar.jpgfile you just created - something likehttps://domain.com/avatars/avatar.jpg- and there you go! Each time you fetch that URL, the image you get will be selected randomly.
What you’re doing is telling Apache to use PHP to interpret the avatar.jpg file, instead of what it would normally do (simply sending the file to the browser).
As you can see, it’s not changing the images every 10 minutes. But itt’s pretty simple and it’s a neat effect.
By the way, you can also use this as a random image for your web site. Just write the usual <img> tag and use the avatar.jpg URL as the src attribute, like this:
<img src="https://domain.com/avatars/avatar.jpg" alt="random image" />
Hope you guys enjoy this! :)
Raúl Santos