php读取目录下的文件

工作需要写了一个读取指定目录下的文件,并显示列表,点击之后读取文件中的内容

高手拍砖,目录可以自由指定,我这里直接写的是获取当前文件目录下面的所有文件

</pre>
<?php
 
/**
 * 读取指定目录下面的文件内容
 * @author Administrator
 *
 */
class Catlog {
 
 /**
 * 要读取的目录
 * @var string
 */
 private $dir;
 
 /**
 * 文件名中必须存在
 * @var string
 */
 private $str = 'ping';
 
 public function __construct() {
 $this->dir = getcwd();
 }
 
 public function test() {
 echo $this->dir;
 }
 
 /**
 * 获取指定目录下面的所有文件
 * @return array
 */
 public function getFile() {
 
 $dirArr = scandir($this->dir);
 $fileInfo = array();
 foreach( $dirArr as $k => $v ) {
 if( !is_dir($v) && strpos($v, $this->str) !== FALSE ) {
 
 $filePath = $this->dir . '/' . $v;
 
 $fileArr['ctime'] = date('Y-m-d', filectime($filePath) );
 $fileArr['mtime'] = date('Y-m-d', filemtime($filePath) );
 $fileArr['atime'] = date('Y-m-d', fileatime($filePath) );
 $fileArr['fileName'] = $v;
 
 $fileInfo[] = $fileArr;
 }
 }
 
 return $fileInfo;
 }
 
 /**
 * 获取某个文件的内容
 * @return multitype:number string
 */
 public function getFileContent() {
 
 if( isset($_GET['file_name']) && !empty($_GET['file_name']) ) {
 $fileName = $_GET['file_name'];
 $fileFullPath = $this->dir . '/' . $fileName;
 
 if( !is_file($fileFullPath) && !file_exists($fileFullPath) ) {
 return $msg = array('error'=>1, 'msg'=>'文件不存在');
 } else {
 $content = file_get_contents($fileFullPath);
 return $msg = array('error'=>0, 'msg'=>nl2br( $content) );
 }
 
 } else {
 return $msg = array('error'=>1, 'msg'=>'文件不存在');
 }
 
 }//end catFileContent
 
 
}
 
$cat = new Catlog();
 
$notic = $cat->getFileContent();
 
if( $notic['error'] == 0 ) {
 echo $notic['msg'];
} else {
 
//显示网页内容
 
?>
 
<!DOCTYPE html>
<html>
 <head>
 <style type="text/css">
 .time{ display:inline-block;
 margin-right:200px;
 float:right;
 }
 ol li { width:1000px; }
 .file-name{ width:260px; display:inline-block; overflow:hidden;
 white-space:nowrap;
 -moz-text-overflow:ellipsis;
 text-overflow:ellipsis; }
</style>
 </head>
 <body>
 <ol>
 <?php foreach($cat->getFile() as $k => $v ):?>
 <li>
 <a class="file-name" href="<?php echo '/catlog.php?file_name=' . $v['fileName'];?>"><?php echo $v['fileName']?></a>
 <span class="time"><?php echo "创建时间:" . $v['ctime'] . "&nbsp;&nbsp;修改时间: " .$v['mtime'] . "&nbsp;&nbsp;上次阅读时间: " .$v['atime']?></span>
 </li>
 <?php endforeach;?>
 </ol>
 </body>
</html>
<?php
}////显示网页内容 END
?>
<pre>

 

posted @ 2015-07-28 21:20  马辉  阅读(304)  评论(0编辑  收藏  举报