您的位置:首页 > 编程语言 > PHP开发

php之简单的文件管理

2014-03-20 11:16 381 查看
++++++++++++++++++++++++++++++++++++++++++++++++++

简单的文件管理

++++++++++++++++++++++++++++++++++++++++++++++++++

1实现目标:通过php的目录和文件的相关函数实现某目录下文件的管理

2相关的函数

opendir - 打开目录句柄

readerdir - 从目录和句柄中读取条目

filectime - 从目录句柄中读取条目

filesize - 取的文件大小

filetype - 取的文件类型
fopen - 打开文件或URL

<?php
//简单的在线文件管理
$path = "./";
//一、根据action的信息值,做对应的操作
switch($_GET['action'])
{
case "del"://删除一个文件信息
unlink($_GET["filename"]);
break;
case "create":
//获取要创建的文件名
$filename=trim($path,"/")."/".$_POST["filename"];
//判断文件是否已经存在
if( file_exists($filename))
{
die ("要创建的文件已经存在");
}
//3创建这个文件
$f = fopen($filename,"w");
fclose($f);
break;
case "edit"://编辑文件信息
//获取文件名
$filename = $_GET["filename"];
//读取文件内容
$fileinfo = file_get_contents($filename);

break;
case "update"://执行修改文件信息
//获取文件名和内容
$filename = $_POST["filename"];
$content = $_POST["content"];
//执行文件内容修改
file_put_contents($filename,$content);
break;
}
//二、浏览指定目录下的文件,并使用表格输出

//path目录信息的过滤,判断path存在,并且是否是目录
if(!file_exists($path)||!is_dir($path))
{
die($path."目录无效!");
}
echo "<h3><a href='file_system.php?action=add'>创建文件</a></h3>";
//输出表头信息
echo "<h3>{$path}目录下的文件是</h3>";
echo "<table width='600' border='0'>";
echo "<tr bgcolor='#cccccc' align='left'>";
echo "<th>序号</th><th>名称</th><th>类型</th><th>大小</th><th>创建时间</th><th>操作</th>";
echo "</tr>";

//打开这个目录,并遍历目录下的文件,并输出文件信息
$dir = opendir($path);
//指定过滤掉的文件
$filtlist=array("file_system.php");
$i=0;
if($dir)
{
while($f = readdir($dir))
{
if($f=="."||$f==".."||in_array($f,$filtlist))
continue;
$file = trim($path,"/")."/".$f;
$i++;
echo "<tr>";
echo "<td>{$i}</td>";
echo "<td>{$f}</td>";
echo "<td>".filetype($file)."</td>";
echo "<td>".filesize($file)."</td>";
echo "<td>".date("Y-m-d H:i:s ",filectime($file))."</td>";
echo "<td><a href='file_system.php?filename={$file}&action=del'>删除</a>
<a href='file_system.php?filename={$file}&action=edit'>编辑</a></td>";
echo "<tr></tr>";
}
closedir($dir);//关闭目录
}
echo "<tr bgcolor='#cccccc' align='left'><td colspan='6'> </td></tr>";

echo "</table>";
//三、、判断是否需要创建文件的表单,若则输出
if($_GET["action"]=="add"){
echo "<form action='file_system.php?action=create' method='post'>";
echo "新建文件:<input type= 'text' name=filename>";
echo "<input type= 'submit' value='新建文件'>";
echo "</form>";
}
//四、判断是否需编辑文件的表单,若则输出
if($_GET["action"]=="edit"){
echo "<form action='file_system.php?action=update' method='post'>";
echo "<input type='hidden'name='filename' value='{$filename}'/>";
echo "文件名:{$filename}<br/><br>";
echo "文件内容:<textarea name='content' cols='40'rows='6'>{$fileinfo}</textarea><br/><br/>";
echo "<input type= 'submit' value='确认编辑'>";
echo "</form>";
}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: