I have the following text file and php code, the text file holds a few minor variables and I would like to be able to update specific variables from a form.
The problem is that when the code is executed on submission it adds extra lines to the text file that prevent the variables from being read correctly from the text document. I have add the text file, code and outcomes below.
Text file:
Title
Headline
Subheadline
extra 1
extra 2
php code:
<?php
session_start();
// Get text file contents as array of lines
$filepath = '../path/file.txt';
$txt = file($filepath);
// Check post
if (isset($_POST["input"]) &&
isset($_POST["hidden"])) {
// Line to edit is hidden input
$line = $_POST['hidden'];
$update = $_POST['input'];
// Make the change to line in array
$txt[$line] = $update;
// Put the lines back together, and write back into text file
file_put_contents($filepath, implode("\n", $txt));
//success code
echo 'success';
} else {
echo 'error';
}
?>
Text file after edit:
Title edited
Headline
Subheadline
extra 1
extra 2
Desired outcome:
Title edited
Headline
Subheadline
extra 1
extra 2
There are two solutions thanks to Cheery and Dagon.
Solution one
Solution two