栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从目录加载随机图像

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从目录加载随机图像

这是我的缓存解决方案:

<?phpdefine('CACHE_FILE', 'mycache.tmp');define('CACHE_TIME', 20); // 20 seconds (for testing!)define('IMG_COUNT', 30);define('IMG_DIR', '../public/wp-content/uploads/2012/01');function LoadListFromCache($cacheFile, $cacheTime){  if ( file_exists($cacheFile) )  {    $fileHandle = fopen($cacheFile, 'r');    if ( !$fileHandle )      return false;    // Read timestamp (separated by "n" from the content)    $timestamp = intval( fgets($fileHandle) );    fclose($fileHandle);    // Expired?    if ( $timestamp+$cacheTime > time() )      return false;    else    {      // Unserialize the content!      $content = file_get_contents($cacheFile);      $content = substr( $content, strpos($content, "n") );      $list = unserialize($content);      return $list;    }  }  return false;}function SaveListToCache($cacheFile, $list){  $fileHandle = fopen($cacheFile, 'w');  if ( $fileHandle === FALSE ) return false;  fwrite($fileHandle, time());  fwrite($fileHandle, "n");  fwrite($fileHandle, serialize($list));  fclose($fileHandle);  return true;}function GenerateList(){  $a = array();  $dir = IMG_DIR;  if ($handle = opendir($dir))  {    while (false !== ($file = readdir($handle)))    {      if (preg_match("/.png$/", $file)) $a[] = $file;      elseif (preg_match("/.jpg$/", $file)) $a[] = $file;      elseif (preg_match("/.jpeg$/", $file)) $a[] = $file;    }    closedir($handle);  }  SaveListToCache(CACHE_FILE, $a);  return $a;}function GetRandomImages($list, $count){  $listCount = count($list);  $randomEntries = array();  for ($i=0; $i<$count; $i++)  {    $randomEntries[] = $list[ rand(0, $listCount) ];  }  return $randomEntries;}// This pre will execute the other functions!$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);if ( $list === FALSE ){  $list = GenerateList();}$images = GetRandomImages($list, IMG_COUNT);foreach ($images as $image){  echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/398093.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号