随机显示图片的PHP代码

这两天又换模版了,想着在adsense广告旁边放上一些随机的图片,就类似于Adsense Beautifier的效果。

找了找,找到这段随机显示图片的代码:

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

使用方法:
下载保存为一个文件,比如random.
将这个文件和图片放在一个文件夹下,再用下面的代码调用:

  1. <img src=".../random.php" alt="random picture" />

也可以加上链接,比如:

  1. <a href="http://www.manboo.info/"><img src=".../random.php" alt="random picture" /></a>

Popularity: 36% [?]

Tags: , ,
Related posts

cirtexhosting_ads.gif

One Response to “随机显示图片的PHP代码”

  1. 显示程式效果不错~

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word