2

我有一个用于编辑 .txt 文件的应用程序。应用程序由 3 个部分组成

  1. 显示包含要编辑的文件的文件夹的内容(每个文件都是一个链接,单击它会在编辑模式下打开)。

  2. 写入文件。

  3. 保存到文件。

第 2 部分和第 3 部分我已经完成了使用并不难的 fopen 和 fwrite 函数。我需要帮助的部分是第一部分,目前我通过输入文件的位置和文件名来打开文件,就像在我有显示功能和保存功能的 php 文件中一样:

$relPath = 'file_to_edit.txt';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath ! ");

但我想要的是文件在单击时以编辑模式打开,而不是每次都输入文件名。

$directory = 'folder_name';

if ($handle = opendir($directory. '/')){
    echo 'Lookong inside \''.$directory.'\'<br><br>';

        while ($file = readdir($handle)) {
        if($file !='.' && $file!='..'){
        echo '<a href="'.$directory.'/'.$file.'">'.$file.'<a><br>';

    }

    }

}

这是 ti 用来显示指定文件夹中文件列表的代码。谁能给我一些指示如何实现这一目标?任何帮助将不胜感激。

4

1 回答 1

3
  1. 要获取文件的内容,请使用 file_get_contents();
  2. 要放置文件的内容,请使用 file_put_contents(); 带有FILE_APPEND标志进行编辑。
  3. 要接收目录中的文件列表,您可以使用 DirectoryIterator

例子:

foreach (new DirectoryIterator('PATH/') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

如果您不想放置文件名,则可以将读取的文件放入 db 中,为它们分配 id 并使用带有 id 参数的链接。另一种解决方案是将文件存储在会话数组中并为它们分配密钥。当您想要获取文件时,您只需要提供密钥而不是整个文件名和路径。

$_SESSION示例

$file_arr = array();
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    $file_arr[] = array("path" => $fileInfo->getPathname(), 'name' => $fileInfo->getFilename());
}
$_SESSION['files'] = $file_arr;

然后在视图中您可以使用

foreach($_SESSION['files'] as $k=>$file)
{
  echo "<a href='edit.php?f=".$k."'>'.$file['name'].'</a>";
}

edit.php

$file = (int)$_GET['f'];

if(array_key_exits($file, $_SESSION['files'])
{
   $fileInfo = $_SESSION[$file'];

   //in file info you have now $fileInfo['path'] $fileInfo['name']
}
于 2013-05-21T06:50:44.520 回答