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


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  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. }
  64. }
  65.  
  66.  
  67.  
  68. ?>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.