Wenn man nicht immer das selbe Bild oder Banner haben will, kann man mit dieser Funktion ein zufälliges Bild aus einem Verzeichnis auslesen und anzeigen.

  1. /**
  2.  * Smarty plugin
  3.  * @package Smarty
  4.  * @subpackage plugins
  5.  *
  6.  *
  7.  * Smarty random_pic function plugin
  8.  *
  9.  * Type: function
  10.  * Name: random_pic
  11.  * Purpose: loads a random pic from dir
  12.  *
  13.  * use: {random_pic dir='path/to/dir' alt='some description' width='300' height='200'}
  14.  * the width and height can be omitted, it will be added automatically
  15.  * but you can use this to overide those values
  16.  *
  17.  * @author Johannes 'Banana' Keßler <mail at bananas-playground dot net>
  18.  * @param array
  19.  * @param Smarty
  20.  */
  21. function smarty_function_random_pic($params, &$smarty)
  22. {
  23. if(!isset($params['dir'])) return false;
  24.  
  25. if(!isset($params['type']))
  26. {
  27. $type = false;
  28. }
  29.  
  30. // check if we have an / at the end
  31. // if not add some
  32. $params['dir'] = str_replace("'","",$params['dir']);
  33. $dir_tmp = substr($params['dir'],-1,1);
  34. if($dir_tmp != "/")
  35. {
  36. $params['dir'] .= "/";
  37. }
  38.  
  39. // read files from dir
  40. // and supress error messages
  41. $files = array();
  42. $dh = @opendir($params['dir']);
  43. while(false !== ($file = @readdir($dh)))
  44. {
  45. if($file[0] ==".") continue;
  46.  
  47. if(is_file($params['dir'].$file))
  48. {
  49. if($params['type'])
  50. {
  51. if(strstr($file,$params['type']))
  52. {
  53. $files[] = $file;
  54. }
  55. }
  56. else
  57. {
  58. $files[] = $file;
  59. }
  60. }
  61. }
  62. @closedir($dh);
  63.  
  64. // if no files are found raise an error
  65. if(!isset($files[0]))
  66. {
  67. $smarty->trigger_error("random_pic: either wrong 'dir', 'type' value or no files available");
  68. return false;
  69. }
  70.  
  71. // get the random pic
  72. $picCount = count($files)-1;
  73. $rand = rand(0,$picCount);
  74. $pic = $files[$rand];
  75.  
  76. // check if we have set the width or height
  77. if(!isset($params['width']) || !isset($params['width']))
  78. {
  79. $picInfo = getimagesize($params['dir'].$pic);
  80. $params['width'] = $picInfo[0];
  81. $params['height'] = $picInfo[1];
  82. }
  83.  
  84.  
  85. // the return code
  86. $out = '<img src="'.$params['dir'].$pic.'" alt="'.$params['alt'].'" width="'.$params['width'].'"
  87. height="'.$params['height'].'" />';
  88.  
  89. return $out;
  90. }