Hello I have a piece of code that writes to a text file, but I want the php file to completely overwrite the content of the text file, not just add to it, how must I rework my code to make it overwrite instead of just write. this is my code:
<form name="savefile" method="post" action="">
<input type="hidden" name="filename" value="code"><br/>
<textarea rows="40" cols="40" name="textdata" style ="font-family: "Lato", sans-serif;">
<?php echo file_get_contents('code.txt'); ?>
</textarea><br/>
<input type="submit" name="submitsave" value="Save">
</form>
<?php
if (isset($_POST)){
if ($_POST['submitsave'] == "Save" && !empty($_POST['filename'])) {
if(!file_exists($_POST['filename'] . ".txt")){
$file = tmpfile();
}
$file = fopen($_POST['filename'] . ".txt","a+");
while(!feof($file)){
$old = $old . fgets($file). "|___end message___|___begin message___|";
}
$text = $_POST["textdata"];
file_put_contents($_POST['filename'] . ".txt", $old . $text);
fclose($file);
}
}
?>
Overwrite is nothing but writing a same file, difference is file pointer is at the beginning of the file when you overrite. You can try with mode 'w'. php.net/manual/en/function.fopen.php
Related
My program uses PHP to open a list of configuration settings from a txt file called "configurationSettings.txt" and puts the data from it onto a form.
What I'm trying to figure out is how to enable my program to update the data on the original txt file if the user changes anything through the form.
Here is an example of the txt file data:
Channel 7
4.0000
6.0000
Here is my code that reads the data and fills my form:
<?php
$configFile = fopen("configurationSettings.txt", "r");
$title1 = fgets($configFile);
$gain1 = fgets($configFile);
$offset1 = fgets($configFile);
fclose($configFile);
?>
<form action="program.php" method="post">
Channel 8 Title:<br>
<input type="text" name="channel0Title" value="<?php echo $title1 ?>">
<br>
Gain:<br>
<input type="text" name="channel0Gain" value="<?php echo $gain1 ?>">
<br>
Offset:<br>
<input type="text" name="Channel0Offset" value= "<?php echo $offset1 ?>">
<br>
<input type="submit" id ="submitButton" value="Submit">
</div>
</form>
And heres a picture of what it looks like:
What do I do to update the original txt file by pressing the submit button?
Tested, works 100%. You don't have to create .txt. Gets created automatically if not present.
index.html
<form action="program.php" method="post">
Channel 8 Title:<br><input type="text" name="channel0Title" value="Channel 7"><br>
Gain:<br><input type="text" name="channel0Gain" value="4.000"><br>
Offset:<br><input type="text" name="channel0Offset" value= "6.000"><br>
<input type="submit" id ="submitButton" value="Submit">
</form>
program.php
<?php
$title = $_POST["channel0Title"]; //You have to get the form data
$gain = $_POST["channel0Gain"];
$offset = $_POST["channel0Offset"];
$file = fopen('configurationSettings.txt', 'w+'); //Open your .txt file
ftruncate($file, 0); //Clear the file to 0bit
$content = $title. PHP_EOL .$gain. PHP_EOL .$offset;
fwrite($file , $content); //Now lets write it in there
fclose($file ); //Finally close our .txt
die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die("There was an error writing this file");
}
else {
echo "$ret bytes written to file";
}}
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.
Why can't I do a proper strpos function on an uploaded file (I first upload the file, and then do a $site = stream_get_line($f, 4096, "\n")) and it works completely fine when read the same thing into $site from a manually created file on the server.
I have no idea what's causing it... it seems to read the line well in both cases, but strpos just doesn't work the same when it's uploaded via user versus when I create it manually.
Here's the code:
<?php
if(!$_FILES){
?>
<head>
<title>Bulk Index Checker</title>
</head>
<center>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br/>
<input type="submit" value="Check 'em!" />
</form>
</center>
<?php
}
else{
echo("<center> <h1>Checking... please wait.</h1> <br><table border=1> <tr><td>Site</td><td>Indexed</td></tr>");
$target_path = "checkupload/";
$target_path = $target_path . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$f = fopen($target_path, "r") or exit("Unable to open file!");
while (!feof($f))
{
$site = stream_get_line($f, 4096, "\n");
$url = 'http://www.google.com/search?q=info:' . $site;
//sleep(3);
$contents = file_get_contents($url);
if (strpos($contents,'<h3 class="r"><a href="/url?q='.$site)!=FALSE) {
echo("<tr bgcolor=\"Silver\"><td>".$site."</td><td>YES</td></tr>");
echo("<br>");
}
else{
echo("<tr><td>".$site."</td><td>NO</td></tr>");
}
}
?>
</table>
<br/>
<form>
</center>
<?php
}
?>
Edit: Here's another way I tried (using textarea) - same thing basically - it ONLY works properly when you input only 1 URL. As soon as you input another URL below, it shows a FALSE for the first one when it's really TRUE.
WHY IS THIS HAPPENING?
<?php
if(!$_POST){
?>
<head>
<title>Bulk Index Checker</title>
</head>
<center>
<h1>Bulk Index Checker v1.0</h1>
<form method="post" enctype="multipart/form-data">
<textarea id="list" name="list" rows="10" cols="50"></textarea>
<br/>
<input type="submit" value="Check 'em!" />
</form>
</center>
<?php
}
else{
echo("<center> <h1>Checking... please wait.</h1> <br><table border=1> <tr><td>Site</td><td>Indexed</td></tr>");
$lines = explode("\n", $_POST['list']);
foreach($lines as $site) {
echo($site);
$url = 'http://www.google.com/search?q=info:' . $site;
sleep(3);
$contents = file_get_contents($url);
if (strpos($contents,'<h3 class="r"><a href="/url?q='.$site)!=FALSE) {
echo("<tr bgcolor=\"Silver\"><td>".$site."</td><td>YES</td></tr>");
echo("<br>");
}
else{
echo("<tr><td>".$site."</td><td>NO</td></tr>");
}
}
?>
</table>
<br/>
</center>
<?php
}
?>
Try to use '!==' instead of '!='.
I don't have an option to test at this stage. See http://php.net/manual/en/function.strpos.php (example #2)
I have the following HTML:
<form method="post" id="print" action="writefile.php" onsubmit="Javascript:window.print(); return true;">
<div id="non-printable">
Enter First & Last Name:
<input id="who" name="who" type="text" /><br><br>
Enter Taken Date:
<input id="tdate" readonly name="todays_date" onfocus="showCalendarControl(this);" type="text" /><br><br>
<input id="submit" type="button" class="btn" value="Submit" />
<div id="printout" style="text-align:center;display:none;">
<input type=submit value="Print Certificate" />
</div>
</div>
</form>
<div id="parent">
<h1>THIS WILL PRINT WHEN 'PRINT CERTIFICATE' IS PRESSED</h1>
</div>
The following CSS:
#media print {
#non-printable { display: none; }
#parent { display: block; }
}
What I am looking to do is when the PRINT CERTIFICATE is pressed I want to write to a file located in my server and also display the Print window as it is currently doing right now. How can I accomplish that?
I know I can use the following PHP but the incorporation is the issue:
<?php
session_start();
// Clean up the input values
foreach($_POST as $key => $value) {
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
$printfor = $_POST['who'];
$dte = $_POST['todays_date'];
$filename = "writefile.txt"; #Must CHMOD to 666, set folder to 777
if($printfor && $dte) {
$text = "\n" . str_pad($_SESSION['printlogin'], 15) . "" . str_pad($printfor, 30) . "" . str_pad($dte, 15);
$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
fwrite ($fp, $text);
fclose ($fp);
#echo ("File written");
}
else {
#echo ("File was not written");
}
}
?>
Append to a file:
Well, if you change your html file, you can incorporate the php into it. You can trigger that php form by making the html button part of a form. When the form submits, the action can be whateveryounamedyourphpfile.php. If you have put hidden input fields on your form (the php you have there is looking for the 'userprint' and 'date' inputs, you can have it write to the file.
The HTML:
<form id="print" method="post" action="whateveryounamedyourphpfile.php" onsubmit="Javascript:window.print(); return true;">
<input type="hidden" name="date" value="yourvaluehere" />
<input type="hidden" name="userprint" value="yourvaluehere" />
<input type="submit" value="Print Certificate" />
</form>
The PHP:
<?php
$printfor = $_post['userprint'];
$date = $_post['date'];
if($printfor && $date) {
$text = "\n" . str_pad($_SESSION['printlogin'], 10) . "" . str_pad($printfor, 25) . "" . str_pad($dte, 15);
$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
fwrite ($fp, $text);
fclose ($fp);
#$writeSuccess = "Yes";
#echo ("File written");
}
else {
#$writeSuccess = "No";
#echo ("File was not written");
}
}
//Echo your HTML here
?>
I created this JS Fiddle for you to get you on your way. http://jsfiddle.net/KEHtF/
It uses .ajax to submit the information to your PHP script while also invoking the print command.
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