当前位置:Gxlcms > PHP教程 > php随机显示指定文件夹下的所有图片

php随机显示指定文件夹下的所有图片

时间:2021-07-01 10:21:17 帮助过:16人阅读

  1. # Init Array
  2. $files = array();
  3. # Get Folder
  4. if($_GET['folder']) {
  5. $folder = $_GET['folder'];
  6. } else {
  7. # Set Default Folder
  8. $folder = '/img/';
  9. }
  10. # Set Full Path
  11. $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $folder;
  12. # Open Directory
  13. if($handle = opendir($path)) {
  14. # Loop Through Directory
  15. while(false !== ($file = readdir($handle))) {
  16. if ($file != "." && $file != "..") {
  17. if(substr($file, -3) == 'gif' || substr($file, -3) == 'png' || substr($file, -3) == 'jpg' || substr($file, -4) == 'jpeg') $files[count($files)] = $file;
  18. }
  19. }
  20. }
  21. # Close Handle
  22. closedir($handle);
  23. # Init Random
  24. $rand = rand(0, count($files)-1);
  25. # Check Header Type
  26. # GIF
  27. if(substr($files[$random], -3) == 'gif') header("Content-type: image/gif");
  28. # JPEG
  29. elseif(substr($files[$random], -3) == 'jpg') header("Content-type: image/jpeg");
  30. elseif(substr($files[$random], -4) == 'jpeg') header("Content-type: image/jpeg");
  31. # PNG
  32. elseif(substr($files[$random],-3) == 'png') header("Content-type: image/png");
  33. # Read File
  34. readfile($path . '/' . $files[$random]);
  35. ?>

人气教程排行