Code to Edit Flat File Entries

Hello everyone,

I am currently working on a control panel for some people who know nothing whatsoever about webpage editing to be able to edit the menu I have posted on their website. I use text file includes to display all the information on the site and I need help with saving the edited data for each section back to its original file. I already have a form set up that inserts new items into the file and then displays the entries below the form within textfields/textareas for editing. The only thing I’m stuck on is how to write each entry that’s listed below the add new entry form back into the file it was read from.

Here is the test form:

And here is the code I’m using:

Bippy's Website Control Panel: Test Editing: Test





$file_name = ‘test.txt’;

// this reads the file into an array
$file_array = file($file_name);

if($_GET[‘action’] == ‘deleteline’){
// a delete request was made, unencode the data
$delete_value = base64_decode($_GET[‘line’]);

// loop through the file array and only include
// the lines that aren't the one we want to delete into
// a  new array
foreach ($file_array as $line => $value) {
    if($delete_value != $value){
        $new_array[] = $value;
// replace the old array with our new one with a
// line removed
$file_array = $new_array;

// collapse the array to a string
$file_data = implode('',$file_array);

// write the data back to the file
$handle = fopen($file_name, 'w+');
fwrite($handle, $file_data);



$item = array();
foreach ($file_array as $line => $value) {
$item = explode(’|’, $value);
echo “

"; } ?>
<input type=‘text’ name=‘item’ value=’”.$item[‘0’]."’><a href=".$_SERVER[‘PHP_SELF’]."?action=deleteline&line=".base64_encode($value).">Delete
<input type='text' size='4' name='price' value='".$item['2']."'

And this is the code that adds the info into the db:
$item = $_POST[‘item’];
$desc = $_POST[‘desc’];
$price = $_POST[‘price’];

$section = $_POST[‘section’];

switch ($section){
case “app”:
$file = “appetizers”;
case “soup”:
$file = “soups”;
case “sides”:
$file = “sides”;
case “sandwiches”:
$file = “sandwiches”;
case “entrees”:
$file = “entrees”;
case “test”:
$file = “test”;

$line = array($item, $desc, $price);

$delimited = implode("|", $line);

$myFile = “test.txt”;

$fh = fopen($myFile, ‘a+’) or die(“can’t open file”);

fwrite($fh, “\r\n”.$delimited);


header (“location:addedit.php”);

PS - I haven’t coded anything in about 5yrs and I was still a noob when I left off… I’m sure there are tons of more efficient ways of accomplishing this, but I would like to use flat files

Any help would be greatly appreciated!

Sponsor our Newsletter | Privacy Policy | Terms of Service