Adding code to .txt file without overwriting it - php

<?php
$fn = "content.txt";
if (isset($_POST['content'])){
$content = stripslashes($_POST['content']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
$old_content = file_get_contents($fn);
fputs($fp, $content."\n".$old_content);
fclose($fp) or die ("Error closing file!");
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="40" name="content"></textarea>
<input type="submit" value="Submit">
</form>
So this is my php code. But it deletes the the previously written data. How do I make it so that the new piece of data is added on a new line? Keeping the last of the data.
Thank you!
<?php
$fn = "content.txt";
if (isset($_POST['content'])){
$content = stripslashes($_POST['content']);
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="40" name="content"></textarea>
<input type="submit" value="Submit">
</form>
Now it doesn't work at all

from fopen manual:
'a' Open for writing only; place the file pointer at the end of the
file. If the file does not exist, attempt to create it.
change
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
to
$fp = fopen($fn,"a") or die ("Error opening file in write mode!");

You can use a or a+ mode instead of w, so you can do:
$fp = fopen($fn,"a") or die ("Error opening file in write mode!");
instead of:
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
From the manual about fopen mode:
'w': Open for writing only; place the file pointer at the beginning of
the file and truncate the file to zero length. If the file does not
exist, attempt to create it.
'a': Open for writing only; place the file pointer at the end of the
file. If the file does not exist, attempt to create it.
'a+': Open for reading and writing; place the file pointer at the end
of the file. If the file does not exist, attempt to create it.

"Now it doesn't work at all"
^--« As per your edit, this will write each entry on a new line:
I changed:
$content = stripslashes($_POST['content']);
to
$content = stripslashes($_POST['content'] . "\n");
Using \n will have all new entries on a new line.
PHP
<?php
$fn = "content.txt";
if (isset($_POST['content'])){
$content = stripslashes($_POST['content'] . "\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="40" name="content"></textarea>
<input type="submit" value="Submit">
</form>
Written to file:
a1
a2
a3
a4
a5
Hello world!!
Testing 123
Written to file one at a time:
a1,a2,a3,a4,a5
Entered in the textarea box as shown and written to file as shown:
Hello world!!
Testing 123
If you want the data to be entered starting from the top, use:
<?php
if (isset($_POST['content'])){
$content = stripslashes($_POST['content'] . "\n");
$file_data = $content;
$file_data .= file_get_contents('content.txt');
file_put_contents('content.txt', $file_data);
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="40" name="content"></textarea>
<input type="submit" value="Submit">
</form>

Change your call to fopen to use append mode instead of write:
$fp = fopen($fn,"a") or die ("Error opening file in write mode!");
Source: http://www.php.net/manual/en/function.fopen.php

observation - since you were using file_get_contents already I want to mention that there is a reverse function for writing:
file_put_contents($fn, $content, FILE_APPEND);
this way you don't even need to open up the text file and load it into memory.
Helpful for logging too.

Related

Trouble Writing back to text file using PHP fwrite from file selected from a dropdown form

I am having trouble writing back to a text file selected from a html form with a dropdown menu, the script is able to read but is unable to write back, returns "Unable to Open File".using PHP fopen and fwrite
This is the index.html code:
<html>
<head></head>
<title>Edit Server Side Text Files</title>
<body>
<form action="function.php" method="post">
<select name="list">
<option value="./files/banned-kdf.txt">banned-kdf.txt</option>
<option value="./files/blackList.txt">blackList.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>
</body>
</html>
And this is the function.php code:
<?php
if(isset($_POST["edit"])) {
$filename = $_POST["list"];
global $filename;
// var_dump($filename);
$myfile = fopen("$filename", "r") or die("Unable to open file!");
$filecontent = fread($myfile,filesize("$filename"));
fclose($myfile);
}
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<textarea name="textareaContent" rows="50" cols="100">
<?
if(isset($filecontent)) { echo $filecontent; }
?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />
</textarea>
<?
//write to text file
if(isset($_POST["update"])) {
// The following two lines are just for troubleshooting and have been commented out.
// echo $_POST["update"];
// var_dump($filename);
$myfile = fopen("$filename", "w") or die("Unable to open file!");
fwrite($myfile, $_POST["textareaContent"]);
fclose($myfile);
}
?>
</form>
<br>
<br>
Return to List Selection
</html>
You're not sending file name in the second form, just code, so, $filename is undefined. Add it in an input hidden:
global $variable; is not useful here, because the variable will not be present on next script execution, when processing the form.
<?php
// Default value for contents:
$filecontent = '';
// Ok, read the file here
if(isset($_POST["edit"])) {
$filename = $_POST["list"];
global $filename; // This will not be useful
$myfile = fopen("$filename", "r") or die("Unable to open file!");
$filecontent = fread($myfile,filesize("$filename"));
fclose($myfile);
}
// If request comes from second form, process it
if(isset($_POST['update'])) {
// Get file name from input hidden
$filename = $_POST["filename"];
$myfile = fopen("$filename", "w") or die("Unable to open file!");
fwrite($myfile, $_POST["textareaContent"]);
fclose($myfile);
// End the script, no need to show the form again
die('File updated successfully.');
}
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<input type="hidden" name="filename" value ="<?php
// Send filename within form
echo $filename;
?>">
<textarea name="textareaContent" rows="50" cols="100">
<?
// No if needed here, we already have a value
echo $filecontent;
?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />
</form>
<br>
<br>
Return to List Selection
</html>
Please check the permission of target file and the folder in this the file is supposed to be.

How to avoid breaks when content textarea is updated and stored

I am using a textarea in which a user can put some content and save the content.
So a file, like example.txt with its content will be saved on the server.
What happens: even if the user does not change the content, and updates it, the content of the textarea will be saved with a couple of breaks before the content.
Below the way I store the content and read it back:
<form class="rafform" method="post">
<input type="hidden" name="editfile" value="<?php echo $dir . '/' . $file; ?>" />
<textarea name="editcontent">
<?php
readfile($dir . '/' . $file); // read content of example.txt ?>
</textarea>
<input type="submit" class="submitmodal edit btn btn-edit " value="Update" />
</form>
After submit, the content will be replaced
if( isset($_POST['editcontent']) ){
$fn = $_POST['editfile'];
$content = stripslashes($_POST['editcontent']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
echo 'Content edited!';
}
If start typing text on the first line, it looks like this:
If I update this text ( so store it) and open it again, it looks like this:
So: why are there a couple of breaks and spaces before the text? (text should be start again in the left upper corner, because I did nothing change)...
Try to use trim(); a PHP function
https://www.w3schools.com/php/func_string_trim.asp
To remove any whitespaces from both sides
Try this :
Don't give some enter between <textarea></textarea>.
And used trim function
str.trim();
<form class="rafform" method="post">
<input type="hidden" name="editfile" value="<?php echo $dir . '/' . $file; ?>" />
<textarea name="editcontent"><?php
readfile($dir . '/' . $file); // read content of example.txt ?></textarea>
<input type="submit" class="submitmodal edit btn btn-edit " value="Update" />
</form>
if( isset($_POST['editcontent']) ){
$fn = trim($_POST['editfile']);
$content = stripslashes($_POST['editcontent']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
echo 'Content edited!';
}

Save text from URL

I found this code. He saves a text file on the server
I want to change it instead to have a textBox and button.
Have the possibility to compose the URL
Example:
www.example.com/index.php?writeText=text
What needs to change in this code to do this?
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
</form>
</body>
<?php
if(isset($_POST['text_box'])) { //only do file operations when appropriate
$a = $_POST['text_box'];
$myFile = "t.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $a);
fclose($fh);
}
?>
Thanks
You use GET instead of POST.
<?php
if(isset($_GET['writeText'])) { //only do file operations when appropriate
$a = $_GET['writeText'];
$myFile = "t.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $a);
fclose($fh);
}
?>

How to edit/update a txt file with php

After I've read a lot of similar problems with the edit/update function on a file and none of it worked I would like to ask for some help.
I am trying to edit a .txt document from php. I have tried these things:
This was the last code which I've read here and didn't work.
$data_to_write = "$_POST[subject]";
$file_path = "text/" + $row['name'];
$file_handle = fopen($file_path, 'w');
fwrite($file_handle, $data_to_write);
fclose($file_handle);
And this is my previous try:
$new_contents = "$_POST[subject]\n";
$path = "text/$row[name]";
file_put_contents($path, $new_contents);
I hope someone would explain me how to do this the right way. Thank you.
This is all of my code:
<?php
if(isset($_GET['id']))
{
$edit = mysql_query("SELECT * FROM text_area WHERE text_id=$_GET[id]");
$row = mysql_fetch_assoc($edit);
$contents = file_get_contents($row['content']);
?>
<form action="" name="form" method="post">
<input type="hidden" name="id" value="<?php echo $row['text_id']; ?>" /><br />
<label for="">Заглавие:</label><br />
<input type="text" name="title" style="width:500px;" value="<?php echo $row['subject'] ?>" /><br />
<select name="opt">
<option value="0"></option>
<?php
$result = mysql_query("SELECT * FROM image_area");
while ($row = mysql_fetch_array($result))
{
echo "<option value=" . $row['path'] . ">" . $row['name'] . "</option>
";
}
?>
</select><input type="button" name="sumbitP" value="Choose" onclick="addtext();" />Image list<br />
<textarea rows="10" cols="50" name="text" id="markItUp"><?php echo $contents ?></textarea><br />
<input type="submit" name="sumbitT" value="Update" />
<input type="reset" value="Reset" />
</form>
<?php
}
?>
<?php
if(isset($_POST['id']))
{
if(mysql_query("UPDATE text_area SET title='$_POST[subject]' WHERE text_id ='$_POST[id]'"))
{
$data_to_write = "" . $_POST['text'];
$file_path = "text/$row[name]";
$file_handle = fopen($file_path, 'w');
fwrite($file_handle, $data_to_write);
fclose($file_handle);
echo '<br><br><p align="center">Everything is ok</p>';
} else {
echo '<br><br><p align="center">Everything is not ok</p>' ;
}
?>
Just to add something which might be useful: I am getting this error which I can't manage to find an answer for with Google.
Warning: fopen(text/) [function.fopen]: failed to open stream: Is a directory in
You just need to change :
$file_path = "text/" + $row['name'];
to this :
$file_path = "text/" . $row['name'];
The concatenation operator in PHP is . (not +)
And make sure the directory text exists, otherwise its better to check and then write :
$data_to_write = $_POST['subject'];
$file_path = "text/" . $row['name'];
if ( !file_exists("text") )
mkdir("text");
$file_handle = fopen($file_path, 'w');
fwrite($file_handle, $data_to_write);
fclose($file_handle);
You can also open file in append mode using fopen() and put whatever you have at the end like
$path = dirname(__FILE__).'/newfile.txt';
$fp = fopen($path, 'a');
if(!$fp){
echo 'file is not opend';
}
fwrite($fp, 'this is simple text written');
fclose($fp);
You need to use file_get_contents to get the text of your file.
$file_path= "text/" . $row['name'];
// Open the file to get existing content
$current = file_get_contents($file_path);
// Append a new person to the file
$data_to_write.= $_POST[subject]."\n";
// Write the contents back to the file
file_put_contents($file_path, $data_to_write);
See Documentation
I prefer to use file_put_contents and set flags in order to add text instead of overwrite the whole file. With flags you can also lock the file if you have multiple script accessing the same file simultaneously.
Here is how:
$file_name = 'text.txt';
$line= "This is a new line\n";
// use flag FILE_APPEND to append the content to the end of the file
// use flag LOCK_EX to prevent other scripts to write to the file while we are writing
file_put_contents($file_name , $line, FILE_APPEND | LOCK_EX);
Here is the full documentation: https://www.php.net/manual/en/function.file-put-contents.php
I think the problem may be the first line :
$data_to_write = "$_POST[subject]";
Replace it with the following :
$data_to_write = "" . $_POST['subject'];
And i highly recommand to protect this with hmtlentities or anything else as it's a direct user input.
I just put the code into a compiler, you are missing a } at the end.

Edit a file with PHP

Ok here is what I have going on.
I am listing the contest of a directory so I can edit and delete files.
The code I am using to do that is below (Other then editing as it does not work).
<?php
$directory = ("enctlfiles/");
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) != false) {
$files[] = $file;
}
closedir($dir);
sort($files);
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>File Name</TH><th>Modified Date</th><th>Entries In File</th><th>Delete | Edit</th></TR>\n");
foreach ($files as $file)
{
if (strpos($file, '.jpg',1)||strpos($file, '.ctl',1) ){
echo "<TR><TD><a href=$directory$file>$file</a></td>";
echo "<td>";
echo date("F d Y H:i:s",filemtime($directory. $file));
echo "<td>";
echo count(file($directory. $file));
echo "<td>";
echo "<a href=enctlfiles/dodelete.php?file=$file>Delete</a> | <a href=enctlfiles/editfile.php?file=$file>Edit</a>";
}
}
?>
That lists all of the files in order in a nice pretty table. The delete function works. The edit one not so much . It is due to me not knowing what I am doing I am sure of it.
Here is the contents of the editfile.php
<form action="edit.php" method="post">
<TEXTAREA NAME="save" COLS=150 ROWS=50 wrap="off">
<?php
$dir = ".";
include($dir. '/' .$_GET['file']);
?>
</textarea>
<P><INPUT TYPE="SUBMIT" VALUE="Update File"><INPUT TYPE="RESET">
</FORM>
That populates the textarea with the file contents when you click on the "Edit" link. I don't know if that is the right way to get the data in there to be able to edit the file.
Here is the contents of the edit.php file:
<?php
//I have tried this but it give me that Unable to open file.
//$org = ($_GET['file']) or exit("Unable to open file!");
//This returns me to the prodsh.php page but does not edit the file.
$org = $_POST['save'] or exit("Unable to open file!");
$copy = $org . date("-m-d-Y-His");
copy($org,$copy);
$f = fopen($org, 'w');
fwrite($f, $_POST['save']);
fclose($f);
header('Location: http://somesite.com/GroveTuckey/itemsetup/prodsh.php');
?>
I think the editfile.php and the edit.php file are jacked up but don't know where.
I am trying to learn this and this site has been very helpful when I get stumped on something so I thank you in advance for the help given.
Also I know the danger of editing files via a webpage. This is not public or on a server that is accessible by the world. Right now I don't want to deal with a database.
I have edited files using the below code:
<form action="doedit.php" method="post">
<TEXTAREA NAME="save" COLS=150 ROWS=50 wrap="off">
<?php
include('somefile.ctl');
?>
</textarea>
<P><INPUT TYPE="SUBMIT" VALUE="Update File"><INPUT TYPE="RESET">
</FORM>
With the contents of doedit.php being:
<?php
$org = 'Somefile.ctl';// This is the name of the file in the form above
$copy = $org . date("-m-d-Y-His");
copy($org,$copy);
$f = fopen('somefile.ctl', 'w');//This is the name of said file also.
fwrite($f, $_POST['save']);
fclose($f);
header('Location: http://somesite.com/GroveTickey/editfile.php');
?>
But since the names of the files can be anything I can't put specific names in the script.
This works great other then having to hardcode file names.
You aren't passing the name of the file back to edit.php. Set the form's action to edit.php?file=<?php echo $_GET['file']; ?>.
El codigo para editar lo hice asi:
---Inicio
<? php
$filename = isset($_GET['file']) ? $_GET['file'] : '';
$directory = ("C:\\Linux\\www\\contenido\\"); // Restrict to this directory...
$fn = $directory . $filename;
if (isset($_POST['content']))
{
$content = stripslashes($_POST['content']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="100" name="content"><?php readfile($fn); ?></textarea>
<hr />
<input type="submit" value="Guardar">
</form>
back to list
And work great

Categories