---
title: "PHP获取文件夹内的图片，并按图片更新时间降序排列"
author: "yd514"
date: "2013-05-07T14:59:06Z"
tags: []
categories: ["Web前端"]
slug: "php"
draft: false
lastmod: "2013-05-07T15:02:19Z"
id: 1861071
url: "https://yd514.iteye.com/blog/1861071"
---

很简单，直接上代码：

    $imgInputId = func::get('imgInputId');   //返回值的图片框id  
    $selectImg = func::get('selectImg');     //已选择的图片名称，带后缀  
    $path = '/usr/local/images/';  
    $dir = @ opendir($path);  
        $fileFormat = array(0 =&gt; ".jpg", 1 =&gt; ".gif", 2 =&gt; ".png", 3 =&gt; ".bmp");  
        while (($file = readdir($dir)) !== false) {  
            $file\_times = filemtime($path.$file) == false ? (filectime($path.$file) == false ? '' : filectime($path.$file)) : filemtime($path.$file);  
            if (in\_array(substr($file, strpos($file, ".")), $fileFormat) && !empty($file\_times)) {  
                $ImgArr\[$file] = $file\_times;  
            }  
        }  
        //按文件修改时间排序  
        arsort($ImgArr);  
        //列出 images 目录中的文件  
        echo "&lt;table width=630 border=0 cellspacing=0 cellpadding=5&gt;&lt;tr&gt;";  
        $file\_num = 0;  
        if(!empty($ImgArr) && count($ImgArr)&gt;0){  
            foreach($ImgArr as $file =&gt;$v ){  
                $file\_num++;  
                echo '&lt;td align=center ';  
                if($file == $selectImg)  
                    echo 'style="border:2px solid #2D4891"';  
                echo '&gt;&lt;a href="###" onclick="javascript:parent.document.getElementById(\\''.$imgInputId.'\\').value=\\'' . $file . '\\';" title="' . $file . '"&gt;&lt;img src="' . $path2 . $file . '" width="50" height="50"&gt;&lt;/a&gt;&lt;br /&gt;' . $file . '&lt;/td&gt;';  
                if ($file\_num % 5 == 0) {  
                    echo "&lt;/tr&gt;";  
                }  
            }  
        }  
        echo "&lt;/tr&gt;&lt;/table&gt;";  
        closedir($dir);

    附：文件属性函数   

    1&gt; filemtime ( string filename )  
    返回文件上次被修改的时间，出错时返回 FALSE。时间以 Unix 时间戳的方式返回，可用于 date()。  
    例如：$a=filemtime("log.txt");  
               echo "修改时间：".date("Y-m-d H:i:s",$a);  
    2&gt; filectime ( string filename )  
    返回文件上次 inode 被修改的时间，如果出错则返回 FALSE。时间以 Unix 时间戳的方式返回。  
    例如：$a=filectime("log.txt");  
               echo "创建时间：".date("Y-m-d H:i:s",$a);  
    3&gt; fileatime ( string filename )  
    返回文件上次被访问的时间，如果出错则返回 FALSE。时间以 Unix 时间戳的方式返回。  
    例如：$a=fileatime("log.txt");  
              echo "修改时间：".date("Y-m-d H:i:s",$a);  
    4&gt; filesize( string filename )  
    函数返回指定文件的大小。若成功，则返回文件大小的字节数。若失败，则返回 false 并生成一条 E\_WARNING 级的错误。  
    例如：echo "文件大小" .filesize("test.txt");