Question

i have an application that is used to edit .txt files. the application is made up of 3 parts

  1. Displays contents of a folder with the files to be edited(each file is a link when clicked it opens on edit mode).

  2. writing in to a file.

  3. saving to file.

part 2 and 3 I have completed using fopen and fwrite functions that wasn't too hard. the part that i need help is part one currently I open the file by inputing its location and file name like so in the php file where i have the display function and save function:

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

but what i want is for the file to open in edit mode when clicked instead of typing in the files name every time.

$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>';

    }

    }

}

this is the code that ti use to display the list of files that are in a specified folder. Can anyone give me some pointers how I can achieve this ? any help will be greatly appreciated.

Was it helpful?

Solution

  1. To get content of file use file_get_contents();
  2. To put content of file use file_put_contents(); with FILE_APPEND flag for editing.
  3. To recieve list of files in directory you can use DirectoryIterator

Example:

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

If you don't want to put filenames you can put read files once put in db assign ids to them and use links with id param. The other solution is to store files in session array and assign keys for them. When you want to get a file you just need to provide key instead of whole filename and path.

Example with $_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;

then in view you can use

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

and 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']
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top