PHP笔记-通过输入获取文件夹中的文件和目录例子
生活随笔
收集整理的這篇文章主要介紹了
PHP笔记-通过输入获取文件夹中的文件和目录例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
程序運行截圖如下:
點擊提交后打印此內容:
文件結構如下:
源碼如下:
dirFile.php
<?phpfunction 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。
總結
以上是生活随笔為你收集整理的PHP笔记-通过输入获取文件夹中的文件和目录例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android逆向笔记-通过tracer
- 下一篇: 动态规划算法php,php算法学习之动态