2011/09/16

Just some note I wrote yesterday

My client wanted to update a webpage with a monthly image, and image extension could be gif, png, jpg, etc. What I need to do is to dynamic check the image in the monthly_tips folder, if there is current month's image, then use it, if not, use the previous month's image, if not, then use a default image.

//get current month, ex: 201109
$ym = date("Ym");

//get last month, ex: 201108
$last_ym = date("Ym",strtotime("-1 months"));

//check if current month's image exists, note that image name like YYYYMM.png, YYYYMM.jpg, etc.
$img = glob("monthly_tips/" . $ym . ".*");
if(count($img) && 0)
  $safty_img = $img[0];
else{//if not found, then check the last month
  $cpath = dirname(__FILE__);
  $img = glob("monthly_tips/" . $last_ym . ".*");
  $default = null;
  //if found the last month's img, then copy it to last.png
  if(count($img)){
    $lastimg = $cpath . "/" . $img[0];
    $path_parts = pathinfo($lastimg);
    $default = 'last.' . $path_parts['extension'];
    $default_path = $cpath . "/monthly_tips/" . $default;
    copy($lastimg, $default_path);
  }
  else{
    $img = glob("monthly_tips/last.*");
    if(count($img))
    $default = $img[0];
  } 
  if($default && file_exists($cpath . "/monthly_tips/" . $default))
    $safty_img = "monthly_tips/" . $default;
  else
    $safty_img = "monthly_tips/default.png"; //worst case;
}

echo $safty_img;


OK, I actually made this way to complicate, and you may not understand what I tried to do here. And my final solution is actually quite simple. The idea is just to use the latest update image in that folder by the following code.

function glob_rsort_latest( $patt ) {
    $rtn = array();
    if ( ( $files = @glob($patt) ) === false ) {
        return $rtn;
    }
    if ( !count($files) ) {
        return $rtn;
    }

    foreach ( $files as $filename ) {
        $rtn[$filename] = filemtime($filename);
    }
    arsort($rtn);
    reset($rtn);
    return $rtn;
}

$files = glob_rsort_latest( 'monthly_tips/*.*' ) ;
if(count($files)){
    $imgs = array_keys($files);
    $safy_img = $imgs[0];
}

No comments:

Post a Comment