使用PHP编辑目录中的文本文件

时间:2013-06-02 23:15:32

标签: php

我有一个脚本,列出了我在目录中的所有txt文件。我已经为每个结果添加了一个超链接,我想重定向到一个简单的编辑器,我有代码。

这是列出目录中文件的代码;

<?php
//Open directory
$dir = dir("content");
//List files in directory
while (($file = $dir->read()) !== false){
    //Make sure it's a .txt file
    if(strlen($file) < 5 || substr($file, -4) != '.txt')
        continue;

    echo "Page: <a href='content/" .$file. "'>" . $file . "</a><br />";
}

$dir->close();
?>

编辑文件的代码:

<?
if($_POST['Submit']){
    $open = fopen("content/body.txt","w+");
    $text = $_POST['update'];
    fwrite($open, $text);
    fclose($open);
    echo "File updated.<br />"; 
    echo "File:<br />";
    $file = file("content/body.txt");
    foreach($file as $text) {
        echo $text."<br />";
    }
}else{
    $file = file("content/body.txt");
    echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
    echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
    foreach($file as $text) {
        echo $text;
    } 
    echo "</textarea>";
    echo "<input name=\"Submit\" type=\"submit\" value=\"Update\" />\n
    </form>";
}
?>

尝试这样做的最佳方式是什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我认为你的意思是:

目录列表中的

使用:

echo "Page: <a href='editor_script.php?filename=".$file."'>".$file."</a><br/>";
编辑器脚本中的

使用:

$open = fopen("content/".$_GET['filename'].".txt","w+");

$file = file("content/".$_GET['filename'].".txt");

我不确定,但您可能需要从action

中移除form
echo '<form method="post">';

或使用带$_GET['filename']

的网址
echo '<form action="editor_script.php?filename='.$_GET['filename'].'" method="post">';

也许这也有效,但我不确定

echo '<form action="?filename='.$_GET['filename'].'" method="post">';