add new lines to text file and get lines from last adding - php

I am working on simple debug script that would allow me (when save button is pushed) to add new lines to .txt file and then on page load, get whatever was saved last time.
so for example i have my user_input.txt file and when i press save - i am adding timestamp and textarea contents to this file. When page is loaded again, i am getting contents from last save.
For the moment i have this code for get:
$current_user_input = file_get_contents('user_input.txt');
if($current_user_input === false) {
$current_user_input = '';
}
and for to set:
if($_POST) {
if($_POST['user_input']) {
$file = 'user_input.txt';
file_put_contents($file, $_POST['user_input']);
}
}
Obviously for the moment its just overwriting the text file and getting all its content, how do i modify it so it does what i described above?

For the save, you need to append the data (as AjAX's comment says using FILE_APPEND), but also adding an end of line to ensure that they appear on separate lines.
if($_POST) {
if($_POST['user_input']) {
$file = 'user_input.txt';
file_put_contents($file, $_POST['user_input'].PHP_EOL, FILE_APPEND);
}
}
You can then retrieve the last line using file() which reads the file in line by line into an array and take the last element...
$oldInput = file($file);
if(!empty($oldInput)) {
$current_user_input = array_pop($oldInput);
}
else {
$current_user_input = '';
}
Update:
For multi-line content you could change the new lines to <br /> tags...
file_put_contents($file,
str_replace( PHP_EOL, '<br />', $_POST['user_input']).PHP_EOL,
FILE_APPEND);
Which would keep all content on a single line.

Related

Delete all lines before a line that included specific word in a file by using php

I need a simple code in php that can delete all lines before a line that included a specific word, for example this is contents of foo.txt:
.
.
eroigjeoj
dvjdofgj
dsfdsft
reytyjkjm
.
.
[DATA]
1,2,4
3,4,5
.
.
.
I want to delete all lines before line that included "[DATA]" and delete that line too.
and the result be a foo.txt with this content:
1,2,4
3,4,5
.
.
.
Here is one approach, maybe not the most efficient.
Create a new text file (text2).
$text2 = fopen("text2", "w");
Initialise a boolean value to false.
$hitWord = false;
Read through original text file (text1) line by line until you hit
the String '[DATA]', adding the subsequent lines to text2
$handle = fopen("text1.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if($hitWord){
fwrite($text2, $line . "\n");
}else{
if(strpos($line,'[DATA]') !== false){
$hitWord = true;
}
}
}
fclose($handle);
} else {
// error opening the file.
}
Delete text1 using unlink($text1) // you will need path
Rename text2 to text1 using rename() function.
ALTERNATIVELY
You could use the same approach above. Except instead of editing a new text file, edit a new String and just replace all the lines in text1 with this string at the end of the program.
This would save you having to create/delete/edit new files. Make sure new line is used correctly

Replace specific line in text file using php while preserving to rest of the file

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
<?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 = $_POST['hidden'];
$update = $_POST['input'] . "\n";
// Make the change to line in array
$txt[$line] = $update;
// Put the lines back together, and write back into txt file
file_put_contents($filepath, implode("", $txt));
//success code
echo 'success';
} else {
echo 'error';
}
?>
Solution two
<?php
session_start();
// Get text file contents as array of lines
$filepath = '../path/file.txt';
$txt = file($filepath);
// Get file contents as string
$content = file_get_contents($filepath);
//check post
if (isset($_POST["input"]) &&
isset($_POST["hidden"])) {
$line = $_POST['hidden'];
$update = $_POST['input'] . "\n";
// Replace initial string (from $txt array) with $update in $content
$newcontent = str_replace($txt[$line], $update, $content);
file_put_contents($filepath, $newcontent);
//success code
echo 'success';
} else {
echo 'error';
}
?>

Find the next empty line in a file

I'm working on a script that edits PHP files contents. So far, i'm able to check if the line is empty on the file and then write what I need into it. However I need to find a way to loop through the array until it finds the next empty line if the first query was not empty.
For example, I want to edit this PHP file - example.php - which contains the following:
<?php
I am not an empty line.
I am not an empty line.
I am not an empty line.
?>
My script:
// File variables
$file = 'path/example.php';
$content = '';
// Check if the file exists and is readable
if (file_exists($file) && is_readable($file)) {
$content = file_get_contents($file);
}
// put lines into an array
$lines = explode("\n", $content);
//Get the fourth line
$Getline = $lines[3];
// check if the line is emptpy
if (empty($Getline) && $Getline !== '0') {
// Write something in the file
}
else {
// Find the next empty line
}
So all I need is to loop through the array until it finds the next empty line. Although I'm not sure how do that.
Use PHP file() function instead of file_get_contents() function. It will read the file in array format itself.
Then you can parse this array using foreach() and can check blank value in it.
May this will help you.
<?php
foreach($lines as $line)
{
// check if the line is empty
if (empty($line) || $line == '')
{
//Line = empty and do stuff here.
}
}
?>

PHP/Txt - How to save into session/load from session

This is quite a long-winded question as im completely lost!
The concept: User inputs a text file they wish to write to, upon submitting they are sent to a page where users can create shapes and submit them to the text file, this data is then used to work out the shapes area, colour that was selected etc...
Issue is how do i write to a text file that is in the session?
This is what i have on the home page:
<?php
// This line starts the session
session_start();
//The below calls the file
$txtFile = $_POST['submittedTxtFile'];
$_SESSION['submittedTxtFile']= $txtFile;
$file = fopen($txtFile, "r") or exit("That file does not exist");
include_once 'classShapeCollection.php';
//Creates the shapecollection
$shapes = new ShapeCollection();
//These lines get the called file, unserialize the $shapes and serialize them again before entering them into the session.
$buffer = fgets($file);
//Checking if there are any contents in the file
if($buffer)
{
$shapes = unserialize($buffer); //unserialize takes Text and turns it into an object
$_SESSION['serial']= serialize($shapes); //Serialize takes the objects and converts them into Text
}
else //if there is nothing in the file, the session serialises the new ShapeCollection
{
$_SESSION['serial']= serialize($shapes);
}
// Closes the called file
fclose($file);
?>
Opening the file as "r" means read only you should open it as write
fopen($txtFile, 'r+')
Or replace 'r+' with 'w+' if you want file to be truncated when opened
After closing the file handler, use file_put_contents() function to update the file. Like this:
fclose($file);
file_put_contents($txtfile, $_SESSION['serial']);
Make sure the file is writable.
Give this a try.
The following will write to a file called TEST.txt taken from the $write_session = "TEST"; session variable.
Base yourself on it, am sure you will get it to work the way you want it to, but that's basically how it will work.
<?php
session_start();
$_POST['submittedTxtFile'] = "file.txt"; // generic filename
$txtFile = $_POST['submittedTxtFile'];
$_SESSION['submittedTxtFile']= $txtFile;
$write_session = "TEST";
$_SESSION['write_session_write'] = $write_session;
$file = fopen($txtFile, "r") or exit("That file does not exist");
echo $_SESSION['submittedTxtFile'];
$file2 = $_SESSION['write_session_write'] . ".txt";
file_put_contents($file2, $write_session);

PHP - Edit/Delete particular line in a file

I have a file users.txt which contains:
"ID" "Access" ;Expire>>26-08-2013<<
"ID" "Access" ;Expire>>27-08-2013<<
"ID" "Access" ;Expire>>28-08-2013<<
I wan't to check if the Expire date is greater than current datetime, and if so I want to add a semicolon at the begin of that line or simply delete that line.
The code i wrote so far for that is following:
$files = file('users.txt');
foreach ($files as $line) {
$pattern = '/>>(.*)<</';
preg_match($pattern, $line, $matches);
$expiredate = strtotime($matches[1]);
$currdate = strtotime(date('d-m-Y'));
if ($currdate > $expiredate) {
echo 'access expired... edit/delete the line<br/>';
} else {
echo 'do nothing, its ok -> switching to the next line...<br/>';
}
}
It retrieves the 'expire date' from every single line from file. It also checks if it's greater than current date but at this point i don't know how to edit (by adding semicolon at the begin) or delete the line which satisfy the condition.
Any suggestions?
Try like this one:
$files = file('users.txt');
$new_file = array();
foreach ($files as $line) {
$pattern = '/>>(.*)<</';
preg_match($pattern, $line, $matches);
$expiredate = strtotime($matches[1]);
$currdate = strtotime(date('d-m-Y'));
if ($currdate > $expiredate) {
// For edit
$line = preg_replace('/condition/', 'replace', $line); // Edit line with replace
$new_file[] = $line; // Push edited line
//If you delete the line, do not push array and do nothing
} else {
$new_file[] = $line; // push line new array
}
}
file_put_contents('users.txt', $new_file);
If you want to edit that line, use preg_match and push edited line to new array.
If you want to delete that line, do nothing. Just ignore.
If you want switching to the next line, push currently line to new array.
At final save new array to file.
The basic process is:
open main file in readonly mode
open secondary (temp) file in writeonly mode
Loop: readline from main file
process the line
save to secondary file
until end of file
close both files
delete the main file
rename the secondary file.

Categories