Jump to content

Php Load Random Image


lastlifelost

Recommended Posts

I was looking at this page: http://.../drop-dead-easy-random-images-via-php/, and was wondering if there was some way to make it work for any file names. As it stands, the code generates a random number which is appended to a file name, i.e. image_x where x corresponds with the random number, thus calling image_1, etc. from a specified directory. This is great, but I'd like to implement this with my existing image files without needing to rename them. I'm very new to PHP, so I don't know what all of the ins and outs are, but here's my envisioned process. Perhaps someone with a little more knowhow could help me put the code together:count the number of images in a directory, outputting this number to a variable $xset up array to create a list of the files, like this one:

<?php$a=array("Dog","Cat","Horse");print_r($a);?>

which would output

Array ( [0] => Dog [1] => Cat [2] => Horse )

Use this information with a random number generator, which would randomize from 1 to $x and would select the image from the numbered array list.I feel like I'm right there on the edge of understanding how to make this happen, but I'm missing some of the needed tools. Can anyone lend me a hammer?

Link to comment
Share on other sites

Using this here function I found on a website via :), you can read the files from a directory into an array:

function dirList ($directory) {	// create an array to hold directory list	$results = array();	// create a handler for the directory	$handler = opendir($directory);	// keep going until all files in directory have been read	while ($file = readdir($handler)) {		// if $file isn't this directory or its parent, 		// add it to the results array		if ($file != '.' && $file != '..')			$results[] = $file;	}	// tidy up: close the handler	closedir($handler);	// done!	return $results;}

Now, you have an array, $results, which should spew out file names if you reference them by index:$results[0] = "random_filename";So, you can generate your random number and use it in place of [0] and you're away.

Link to comment
Share on other sites

Thanks for the post! Here's the final product:

<?php $dir=('some/images/directory');$files=scandir($dir);$y=-1;foreach ($files as $count)//sets the maximum number of images in a directory 	{		$y++;	}$x=rand(0,$y);$z=0;while	(z<=1)	{		if (is_dir($dir . DIRECTORY_SEPARATOR . $files[$x]))	//prevents directories and folder from 		{			$x=rand(0,$y);			  continue;	  }	  elseif (eregi('^[a-zA-Z0-9._-]+\.([dbhtml]{2,4})$', $files[$x]))	//prevents .db and .html files displaying			{			$x=rand(0,$y);			  continue;	  }		else	{			break;			}	}echo <<<images	<br />	<br />	<img alt='$files[$x]' src='$dir/$files[$x]' height='xxx' width='xxx' />images;						?>

Link to comment
Share on other sites

That looks incredibly confusing, why not just do something like

$image = array_rand(glob("some/images/directory/*.png"));echo "<img src=\"$image\">";

Also, note you should use CSS margins, not arbitrary break tags, to add spacing.

Link to comment
Share on other sites

And here I was, all happy that I'd figured out the solution to my problem and you have to come in with this simple two-liner code that puts mine to shame. java script:add_smilie(":)","smid_35")I had no idea that this was an option. Now, how does this work if the directory has multiple image types in it? Also, as I like to understand what my codes are doing and what they're contructed of, what is the "glob" portion of the array?As for the linebreaks being used for spacing, that's really only there for the testing page to provide a little room between the top of the browser and the poor lonely single image that it was generating while testing. The final implementation would have removed those and wrapped the images in their own CSS-styled divs.::EDIT:: I attempted to use the script you provided and it returned blank images. When I checked the source of the page, the image source was reading as a random number rather than a file path. I was able to correct the issue with this edit:

<?php$dir=('some/image/directory/');$files=glob($dir . "*.jpg");$image = array_rand($files);echo "<img src=\"$files[$image]\" >";?>

I'm still curious how to make this work for multiple file types, however.::EDIT 2:: The code below allows this to work with multiple file types and adds an alt tag for the image:

$dir=('some/image/directory/');$files=glob($dir . "{*.jpg,*.png}", GLOB_BRACE);$image = array_rand($files);$alt = pathinfo($files[$image],PATHINFO_BASENAME);echo "<img src=\"$files[$image]\" alt=\"$alt\" >";

Link to comment
Share on other sites

Whoops, that's right, array_rand() returns the index of a random element, not the element itself. And mm, glob() is a very useful function that has done to PHP filesystem reading what java.util.Scanner has done to Java input handling :) Pity it doesn't handle full regex. This should work too:

$files=glob("$dir*.{jpg,png}", GLOB_BRACE);

Link to comment
Share on other sites

Good call on the update - anything to streamline the code, right?Now I'm wondering how I can take the implemented code (below) and filter out the duplicate images. Right now it generates 6 random images with a high probability for doubles. I've even managed to get 4 identical images to show up at once!http://woodturningvt.com/betapage.php

<div class="pagecontent">		<div class="images">		<?php	//	RANDOM IMAGE GENERATOR	//		$array = array('floatleft','floatright','centered');		foreach ($array as $loop)		{	  $dirarray = array('bowls','platters','other');		  $dpath = array_rand($dirarray);	  $dir = 'images/products/' . $dirarray[$dpath] . '/thumbs';	  $images=glob("$dir/{*.jpg,*.png}", GLOB_BRACE);	  $image = array_rand($images);	  $alt = pathinfo($images[$image],PATHINFO_BASENAME);	//for image alt text	  	  echo "<div class='imgcontainer $loop'><img src='$images[$image]' alt='$alt' height='120' width='160' /></div>\n";		}		?>			  </div>  <!-- END .images -->  	Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum rutrum vestibulum ipsum, vulputate interdum elit consequat et. Vivamus porta ullamcorper odio in pretium. 		<div class="images">		<?php	//	RANDOM IMAGE GENERATOR	//		$array = array('floatleft','floatright','centered');		foreach ($array as $loop)		{	  $dirarray = array('bowls','platters','other');		  $dpath = array_rand($dirarray);	  $dir = 'images/products/' . $dirarray[$dpath] . '/thumbs';	  $images=glob("$dir/{*.jpg,*.png}", GLOB_BRACE);	  $image = array_rand($images);	  $alt = pathinfo($images[$image],PATHINFO_BASENAME);	//for image alt text	  	  echo "<div class='imgcontainer $loop'><img src='$images[$image]' alt='$alt' height='120' width='160' /></div>\n";		}		?>

Link to comment
Share on other sites

glob the images into three different shuffled arrays outside the loop. use next() to select the image from an array by random selection of three arrays.building the arrays outside the loop should avoid the duplication issue.

Link to comment
Share on other sites

You could also shuffle the array and then pop off however many you want, there won't be duplicates. e.g.:

$images=glob("$dir/{*.jpg,*.png}", GLOB_BRACE);shuffle($images);$num_images = 5;for ($i = 0; $i < $num_images; $i++){  $image = array_pop($images);  echo $image;}

Link to comment
Share on other sites

The shuffle seems to be the right answer. I didn't use the array_pop, I used foreach loops and nexts instead. I wasn't really sure how the pop would work since I have two different areas in the code that using this php that are separated by yet undetermined amount of filler between them.

<div class="images"><?php	//	RANDOM IMAGE GENERATOR	//	$dir1=glob("images/products/green/thumbs/{*.jpg,*.png}", GLOB_BRACE);	$dir2=glob("images/products/production/thumbs/{*.jpg,*.png}", GLOB_BRACE);	$dir3=glob("images/products/other/thumbs/{*.jpg,*.png}", GLOB_BRACE);	$images=array_merge($dir1,$dir2,$dir3);	shuffle($images);				$array = array('floatleft','floatright','centered');	foreach ($array as $loop)	{	  	  $image = next($images);	  $alt = pathinfo($image,PATHINFO_BASENAME);	//for image alt text	  echo "<div class='imgcontainer $loop'><img src='$image' alt='$alt' height='120' width='160' /></div>\n";							}?></div>  <!-- END .images -->  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum rutrum vestibulum ipsum, vulputate interdum elit consequat et. Vivamus porta ullamcorper odio in pretium. </p><div class="images"><?php	//	RANDOM IMAGE GENERATOR CONTINUED	//	$array = array('floatleft','floatright','centered');	foreach ($array as $loop)	{	  	  $image = next($images);	  $alt = pathinfo($image,PATHINFO_BASENAME);	//for image alt text	  echo "<div class='imgcontainer $loop'><img src='$image' alt='$alt' height='120' width='160' /></div>\n";							}?></div>  <!-- END .images -->

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...