程序运行截图如下:
点击提交后打印此内容:
文件结构如下:
源码如下:
dirFile.php
- <?php
- function dirFile($dir, &$error){
-
- if(!is_dir($dir)){
-
- $error = "路径错误";
- return false;
- }
-
- static $output = array();
- $files = scandir($dir);
- foreach ($files as $file){
-
- $tmp_file = $dir . "/" . $file;
- if(is_dir($tmp_file)){
-
- $output[] = array(
- "fileName" => $file,
- "directory" => $dir,
- "isDir" => true
- );
-
- if($file == "." || $file == ".."){
-
- continue;
- }
- }
- else{
-
- $output[] = array(
- "fileName" => $file,
- "directory" => $dir,
- "isDir" => false
- );
- }
- }
-
- return $output;
- }
- ?>
getFile.php
- <?php
- $dir = $_GET["dir"] ?? '';
- if(!is_dir($dir)){
-
- echo "路径无效";
- header("refresh:3; url=index.html");
- exit;
- }
-
-
- include_once "dirFile.php";
- $files = dirFile($dir, $error);
- if(!$files){
-
- echo $error;
- header("refresh:3; url=index.html");
- exit;
- }
-
- // echo "<pre>";
- // print_r($files);
- // var_dump($files);
- // echo "</pre>";
-
- include_once "list.html"
- ?>
index.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" http-equiv="content-type" content="text/html">
- <title>首页</title>
- </head>
- <body>
- <form action="getFile.php" method="get">
- 输入目录: <input type="text" name="dir" value="" />
- <input type="submit" name="submit" value="提交" />
- </form>
- </body>
- </html>
list.html
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html;charset=utf-8" />
- </head>
- <body>
- <table border=1>
- <p style=""><?php echo $dir;?>目录文件列表</p>
- <tr><th>序号</th><th>文件名字</th><th>文件类型</th></tr>
- <?php $index=1;?>
- <?php foreach($files as $file):?>
- <?php if($file['fileName']=='.'||$file['fileName'] == '..')continue;?>
- <tr>
- <td><?php echo $index++;?></td>
- <td>
- <?php echo $file['fileName'];?>
- </td>
- <td><?php echo $file['isDir']? '文件夹' : '文件';?></td>
- </tr>
- <?php endforeach;?>
- </table>
- </body>
- </html>
这里有几个要注意的地方:
①dirFile.php中scandir($dir)函数获取$dir中的文件和目录;
②dirFile.php中is_dir($file)函数判断$file是文件还是目录;
③getFile.php中header("refresh:3; url=index.html")是告诉浏览器,3s后重定向到index.html。