27
Dec '11

Display Random Image with PHP

I use this script to display a random avatar for my profile on a chatroom. Stick your images in a subfolder called ‘avatars’ and reference this script as if it were an image and you’re away.

$extList = array('gif' => 'image/gif','jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png');

if($handle = opendir(getcwd() . '/avatars')) {
	$pics = array();

	while (false !== ($file = readdir($handle))) {
		if($file != '.' && $file != '..') array_push($pics, $file);
	}

	closedir($handle);

	$img = $pics[array_rand($pics)];

	$imageInfo = pathinfo($img);

	header ("'Content-type: ".$extList[$imageInfo['extension']]."'");
	@readfile('avatars/' . $img);
}

Leave a Reply