Posted By

catchamonkey on 01/23/08


Tagged

php image random banners


Versions (?)

Who likes this?

7 people have marked this snippet as a favorite

helloyj
catchamonkey
mbcdg
uisluu
LordBumpet
vali29
nb109


Display random image from a directory in a standard img src using php


 / Published in: PHP
 

URL: http://www.purpleoak.co.uk

  1. <?php
  2.  
  3. // set the $folder to the folder containing the images
  4. // You then use <img src="/path/to/this/script.php" alt="image randomiser" />
  5. // to display them
  6.  
  7. $folder = 'banners';
  8.  
  9. $extList = array();
  10. $extList['gif'] = 'image/gif';
  11. $extList['jpg'] = 'image/jpeg';
  12. $extList['jpeg'] = 'image/jpeg';
  13. $extList['png'] = 'image/png';
  14.  
  15.  
  16. $img = null;
  17.  
  18. if (substr($folder,-1) != '/') {
  19. $folder = $folder.'/';
  20. }
  21.  
  22. if (isset($_GET['img'])) {
  23. $imageInfo = pathinfo($_GET['img']);
  24. if (
  25. isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
  26. file_exists( $folder.$imageInfo['basename'] )
  27. ) {
  28. $img = $folder.$imageInfo['basename'];
  29. }
  30. } else {
  31. $fileList = array();
  32. $handle = opendir($folder);
  33. while ( false !== ( $file = readdir($handle) ) ) {
  34. $file_info = pathinfo($file);
  35. if (
  36. isset( $extList[ strtolower( $file_info['extension'] ) ] )
  37. ) {
  38. $fileList[] = $file;
  39. }
  40. }
  41. closedir($handle);
  42.  
  43. if (count($fileList) > 0) {
  44. $imageNumber = time() % count($fileList);
  45. $img = $folder.$fileList[$imageNumber];
  46. }
  47. }
  48.  
  49. if ($img!=null) {
  50. $imageInfo = pathinfo($img);
  51. $contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
  52. header ($contentType);
  53. readfile($img);
  54. } else {
  55. if ( function_exists('imagecreate') ) {
  56. header ("Content-type: image/png");
  57. $im = @imagecreate (100, 100)
  58. or die ("Cannot initialize new GD image stream");
  59. $background_color = imagecolorallocate ($im, 255, 255, 255);
  60. $text_color = imagecolorallocate ($im, 0,0,0);
  61. imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
  62. imagepng ($im);
  63. imagedestroy($im);
  64. }
  65. }
  66.  
  67.  
  68.  
  69. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: reptkeu on February 26, 2010

Hello, Would it be easily possible to developp the code so differnt images can be displayed at once on a web page?

You need to login to post a comment.