通过目录处理函数实现文件浏览功能
程序员文章站
2022-07-01 14:35:14
...
一 代码
index.php
<html> <head> <title>文件浏览</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <style type="text/css"> <!-- a:link {text-decoration: none;} a:visited {text-decoration: none;} a:hover {text-decoration: none;} a:active {text-decoration: none;} .style1 {font-size: 12px} --> </style></head> <body><h3 align="center">文件浏览</h3> <div align="center"> <table width="500" height="28" border="1" align="center" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="#999999"> <tr align="center" valign="middle" bgcolor="#A5F5BF" > <th width="100" height="25" align="center" valign="middle" bgcolor="#FFFFFF"><span class="style1">项目名</span></th> <th width="60" align="center" valign="middle" bgcolor="#FFFFFF"><span class="style1">大小</span></th> <th width="150" align="center" valign="middle" bgcolor="#FFFFFF"><span class="style1">创建日期</span></th> <th width="180" align="center" valign="middle" bgcolor="#FFFFFF"><span class="style1">最后修改时间</span></th> </tr> <?php if(!isset($_GET[catalog])||empty($_GET[catalog]))$dqml=getcwd();//获得脚本目录 else $dqml=$_GET[catalog]; chdir($dqml);//改变当前目录 echo "当前目录:".getcwd()."<br>"; $ml = opendir($dqml); //打开目录 while ($hqml = readdir($ml)){ //循环读取目录中的目录及文件 echo "<tr><td align='center' valign='middle' bgcolor='#FFFFFF'>"; if(is_dir($hqml)){ //判断是目录 if($hqml=="."){ $catalog=getcwd();//显示当前目录 echo "<a href=$php_self?catalog=$catalog><span class='style1'>锁定</span></a>"; } elseif($hqml==".."){ $catalog=getcwd()."\\.."; //上级目录 echo "<a href=$php_self?catalog=$catalog><span class='style1'>上级目录</span></a>"; }else{ $catalog=getcwd()."\\$hqml"; //子目录 echo "<a href=$php_self?catalog=$catalog>$hqml</a>"; } }else{ $ext=substr($hqml,strrpos($hqml,".")); if(strtoupper($ext)==".PHP"||strtoupper($ext)==".TXT"){ $catalog=getcwd(); echo "<a href=./indexs.php?catalog=$catalog&filename=$hqml&type=$ext>$hqml</a>"; }else{ echo "$hqml"; } } if(is_dir($hqml)) $file_size="目录"; else $file_size=round(filesize($hqml)/1024)."k"; echo "<td align='center' valign='middle' bgcolor='#FFFFFF'>$file_size</td>"; $create_time=date("y-m-d h:i:sA",filectime($hqml)); echo "<td align='center' valign='middle' bgcolor='#FFFFFF'>$create_time</td>"; $update_time=date("y-m-d h:i:sA",filemtime($hqml)); echo "<td align='center' valign='middle' bgcolor='#FFFFFF'>$update_time</td>"; } closedir($ml); ?> </table> </div> </body> </html>
indexs.php
<html> <head> <title>文件浏览</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body> <a href="index.php">返回目录</a><br> <?php $catalog=$_GET[catalog]; //获取文件的信息 $filename=$_GET[filename]; $type=$_GET[type]; //显示PHP文件的内容 if(strtoupper($type)==".php"){ readfile($catalog."\\".$filename); }else{ //显示txt文件的内容 $fp=fopen($catalog."\\".$filename,"r"); while($line=fgets($fp)){ $line=htmlentities($line,ENT_COMPAT,"GB2312"); echo $line; } fclose($fp); } ?> </body> </html>
二 运行结果