欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-06-09 10:50:18
...
  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. ?>
复制代码