How to save textarea to file php - php

I want to save text in textarea to file but it don't save, when I enter text into textarea and press button "Save", it look like at the firt, no change.
My code here:
<?php
if($_POST['textpackages']){
$content = $_POST['content'];
$file = "http://baokool.net/Packages";
$Saved_File = fopen($file, 'a+');
fwrite($Saved_File, $content);
fclose($Saved_File);
} else {
echo 'ERROR';
}
?>
<form action="test.php" method="post">
<textarea name="content">
<?php
echo file_get_contents("http://baokool.net/Packages");
?>
</textarea>
<input type="submit" name="submit" value="Save">
</form>
Please help me. Thank you very much.
Sorry because my English is bad.

You can't edit a file through HTTP like you're trying to do. You need to use a local file, i.e.:
$content = $_POST['content'];
$file = "yourfile"; // cannot be an online resource
$Saved_File = fopen($file, 'a+');
fwrite($Saved_File, $content);
fclose($Saved_File);

If this script is running on the same Server where you want to save the file, you can write a string into a file with "file_put_contents"(php.net).
Just think about the permissions you need to save a file, thats probably why it isn't working.
If you are trying to save it through HTTP, I think this is not possible.

Related

Get text from .txt and display in text box and then save it with edits made?

I have posted the original PHP code below.
<?php
// configuration
$url = 'home.php';
$file = 'Biden.txt';
// check if form has been submitted
if (isset($_POST['text']))
{
// save the text contents
file_put_contents($file, $_POST['text']);
// redirect to form again
header(sprintf('Location: %s', $url));
printf('Moved.', htmlspecialchars($url));
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
I first added this line of code <?php echo $_POST["potus"]; ?> to $file = 'Biden.txt'; so it looked like this $file = '<?php echo $_POST["potus"]; ?>.txt';, but that did not work, the page is blank.
So then I remembered asking this question Display info from text file based on name submited in a form?, and the answer to that question was replace the one line of code from this $file = fopen("<?php echo $_POST["potus"]; ?>.txt", "r") or exit("unable to open file!"); to $file = fopen($_POST["potus"] . ".txt", "r") or exit("unable to open file!"); as that worked for that answer, but when I use that same line of coding to replace this line of coding $file = 'Biden.txt'; the page is not blank the text box that should be showing the info that is on the Biden.txt file is not showing.
On the line of code that is pulled from the other question, I did have to make one edit and that was change the r to a+ as that show show the text box, but it is still blank. I can type int the box and save the changed, just won't read from the text file.
What I am trying to do is, if I type in i.e. http://name.tld/edit?potus=Biden, it will display what is save in the text file and show it on a text box to where I can make an edit and then save it.

Rewrite a file with PHP using HTML form

So I'm working on a little php file that is supposed to alter a specific file for the user. It gets the contents of the file and puts them into a textarea within a form. How can I make it so any edits done within this textarea will be rewritten to the file on the server? And even better, would I be able to allow the user to only edit certain lines, and have only those lines be rewritten?
Here's my code so far:
<?php
$filename = "../tree_c/index.php";
//$fp = fopen ($filename, "w"); <- doesn't seem to work for it opens empty file.
$contents = file_get_contents($filename);
/*
if (isset($_POST['field'])) {
// something here to rewrite the file.
*/
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<textarea name="field"><?php echo $contents ?></textarea>
<input type="submit" value="Save">
</form>
This should work fairly easily:
if (isset($_POST['field'])) {
file_put_contents($filename, $_POST['field']);
}
$datafile = "Files.txt";
$fp = fopen($datafile, "r");
$textdata= fgets($fp, 1024);
$text = '"'.$textdata.'"';
$this->set('text',$text);
if(!empty($this->data))
{
$datas = $this->data['data']['text']; //(your Textarea name)
$myFile = "Files.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $datas);
fclose($fh);
}
hope this ll help you....

php form writes to txt

I am completely new to php. And have been following tutorials. I need to accomplish making a form which calls a php function which takes the input of the form and writes it to a file. Should be easy enough? I have tried this in many ways and this is the close I have gotten. However for some reason it writes works three times meaning three entries imputed then everything after the third is ignored. test.txt is the file which I write to.
<?php
$email= $_POST['email'];
$myFile = "test.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "$email\n";
fwrite($fh, $stringData);
fclose($fh);
?>
Here is the form I use to use the php.
<div id="login-box">
<form name="form" method="post" action="<?php $_SERVER['PHP_SELF'];?>">
<div class="text-field">
<input name="email" id="email" type="text">
</div>
<input id="login" type="submit" value="Submit">
</form>
</div>
I have tested your code and there is not any problem whatever you are mentioning.The code is inserting more than three record.So please carry on ...
Try to use this example
<?php
$email= $_POST['email'];
$myFile = "test.txt";
// First, let's make sure that the file exists and is writable.
if (is_writable($myFile)) {
// In our example we're opening $ myFile in the "append".
if (!$handle = fopen($myFile, 'a')) {
echo "Can't open ($myFile)";
exit;
}
if (fwrite($handle, $email) === FALSE) {
echo "Can't wtire to file ($myFile)";
exit;
}
echo "OK. Content ($email) written to file ($myFile)";
fclose($handle);
} else {
echo "File $myFile not available for writing.";
}
?>
Also you can simply debug your php code using this code:
echo <something_what_you_need>; die;
Maybe your code called multiple times and you can't see it.
Your Code should work but you wrote <? and not <?php in your form's action attribute.
Add these 2 lines at the top of your PHP code
ini_set('display_errors',1);
error_reporting(E_ALL);
and see the real error message, not your silly "can't open" but the explanation, what is certainly going wrong.
If you can't get it's meaning yourself, post it here, exact and whole.
Maybe you submit form 3 times or push reload button on your browser panel ?
can you post your html ?
and try this:
<?php
if($_POST['email'])
{
$email= $_POST['email'];
$myFile = "test.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "$email\n";
fwrite($fh, $stringData);
fclose($fh);
}
?>

File I/O to textarea in PHP

My friend and I have a little spare time home page together. He's not a programmer, and in order for him to be able to change some text on the front page, I created a php-script that
1) Reads data from file "tester.txt" (this is the text that should go on the front page)
2) Prints this text to a textarea, where you can edit the text and submit it again
3) Writes the edited text to the same file, "tester.txt"
The two functions Read(); and Write(); look like this
function Read() {
$file = "tester.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, filesize($file));
echo "$data <br>";
}
fclose($fp);
}
function Write() {
$file = "tester.txt";
$fp = fopen($file, "w");
$data = $_POST["tekst"];
fwrite($fp, $data);
fclose($fp);
}
The only problem I have is that when the text is printed to a text area the line returns are written as <br> - and I don't really want it to do that, because when you edit some of the code and rewrites it, another layer of <br>'s appear. Here's a screenshot to illustrate:
Is there any workaround to this?
Thanks!
If you need the rest of the code, here it is:
<html>
<head>
<title>Updater</title>
</head>
<body>
<?php
function Read() {
$file = "tester.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, filesize($file));
echo "$data <br>";
}
fclose($fp);
}
function Write() {
$file = "tester.txt";
$fp = fopen($file, "w");
$data = $_POST["tekst"];
fwrite($fp, $data);
fclose($fp);
}
?>
<?php
if ($_POST["submit_check"]){
Write();
};
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<textarea width="400px" height="400px" name="tekst"><?php Read(); ?></textarea><br>
<input type="submit" name="submit" value="Update text">
<input type="hidden" name="submit_check" value="1">
</form>
<?php
if ($_POST["submit_check"]){
echo 'Text updated';
};
?>
</body>
</html>
This is simpler than you think. You shouldn't be outputting the <br> tags as the textarea already contains the entered newline characters (\r\n or \n). You don't have to read the file like that, if you read it this way, you never have to worry about the character contents.
Change:
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, filesize($file));
echo "$data <br>";
}
fclose($fp);
to:
echo file_get_contents( $file);
Problem solved.
This is happening because while writing the contents to the text area, you're putting a <br> at the end of each line. But in a textarea line breaks are noted by "\n". When you're saving your existing text, the next time the line breaks are replaced with more <br>.
While printing out the content on a public page, keep the . But in the editing page, remove the br.
Here's what I would have done with the PHP code:
<?php
define("FILE_NAME", "tester.txt");
function Read()
{
echo #file_get_contents(FILE_NAME);
}
;
function Write()
{
$data = $_POST["tekst"];
#file_put_contents(FILE_NAME, $data);
}
?>
<?php
if ($_POST["submit_check"])
{
Write();
}
?>
You use echo "$data <br>"; - just make that echo $data; ?
At a guess, this is hosted on a *nix machine, and he is using a Windows machine to do the editing?
If this is the case, changing your write function to this should solve the problem:
function Write(){
$file = "tester.txt";
$fp = fopen($file, "w");
$data = str_replace(array("\r\n","\r"),"\n",$_POST["tekst"]);
fwrite($fp, $data);
fclose($fp);
};
You don't need the <br>'s. Depending how your <textarea> is configured, by default lines are hard wrapped using \n's. These are preserved when you save the file, therefore you don't need to add your own line breaks.
Use regex to replace the break tag with a newline character
preg_replace('#<br\s*/?>#i', "\n", $data);
You can find a more detailed explanation answered here

Need to write at beginning of file with PHP

I'm making this program and I'm trying to find out how to write data to the beginning of a file rather than the end. "a"/append only writes to the end, how can I make it write to the beginning? Because "r+" does it but overwrites the previous data.
$datab = fopen('database.txt', "r+");
Here is my whole file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Facebook v0.1</title>
<style type="text/css">
#bod{
margin:0 auto;
width:800px;
border:solid 2px black;
}
</style>
</head>
<body>
<div id="bod">
<?php
$fname = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$comment = $_REQUEST['comment'];
$datab = $_REQUEST['datab'];
$gfile = $_REQUEST['gfile'];
print <<<form
<table border="2" style="margin:0 auto;">
<td>
<form method="post" action="">
First Name :
<input type ="text"
name="fname"
value="">
<br>
Last Name :
<input type ="text"
name="lname"
value="">
<br>
Comment :
<input type ="text"
name="comment"
value="">
<br>
<input type ="submit" value="Submit">
</form>
</td>
</table>
form;
if((!empty($fname)) && (!empty($lname)) && (!empty($comment))){
$form = <<<come
<table border='2' width='300px' style="margin:0 auto;">
<tr>
<td>
<span style="color:blue; font-weight:bold;">
$fname $lname :
</span>
$comment
</td>
</tr>
</table>
come;
$datab = fopen('database.txt', "r+");
fputs($datab, $form);
fclose($datab);
}else if((empty($fname)) && (empty($lname)) && (empty($comment))){
print" please input data";
} // end table
$datab = fopen('database.txt', "r");
while (!feof($datab)){
$gfile = fgets($datab);
print "$gfile";
}// end of while
?>
</div>
</body>
</html>
The quick and dirty:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
If you don't want to load the entire contents of the file into a variable, you can use PHP's Streams feature:
function prepend($string, $orig_filename) {
$context = stream_context_create();
$orig_file = fopen($orig_filename, 'r', 1, $context);
$temp_filename = tempnam(sys_get_temp_dir(), 'php_prepend_');
file_put_contents($temp_filename, $string);
file_put_contents($temp_filename, $orig_file, FILE_APPEND);
fclose($orig_file);
unlink($orig_filename);
rename($temp_filename, $orig_filename);
}
What this does is writes the string you want to prepend to a temporary file, then writes the contents of the original file to the end of the temporary file (using streams instead of copying the whole file into a variable), and finally removes the original file and renames the temporary file to replace it.
Note: This code was originally based on a now-defunct blog post by Chao Xu. The code has since diverged, but the original post can be viewed in the Wayback Machine.
I think what you can do is first read the content of the file and hold it in a temporary variable, now insert the new data to the beginning of the file before also appending the content of the temporary variable.
$file = file_get_contents($filename);
$content = 'Your Content' . $file;
file_put_contents($content);
Open a file in w+ mode not a+ mode.
Get the length of text to add ($chunkLength)
set a file cursor to the beginning of the file if needed
read $chunkLength bytes from the file
return the cursor to the $chunkLength * $i;
write $prepend
set $prepend a value from step 4
do these steps, while EOF
$handler = fopen('1.txt', 'w+');//1
rewind($handler);//3
$prepend = "I would like to add this text to the beginning of this file";
$chunkLength = strlen($prepend);//2
$i = 0;
do{
$readData = fread($handler, $chunkLength);//4
fseek($handler, $i * $chunkLength);//5
fwrite($handler, $prepend);//6
$prepend = $readData;//7
$i++;
}while ($readData);//8
fclose($handler);
You can use the following code to append text at the beginning and end of the file.
$myFile = "test.csv";<br>
$context = stream_context_create();<br>
$fp = fopen($myFile, 'r', 1, $context);<br>
$tmpname = md5("kumar");<br>
//this will append text at the beginning of the file<br><br>
file_put_contents($tmpname, "kumar");<br>
file_put_contents($tmpname, $fp, FILE_APPEND);<br>
fclose($fp);<br>
unlink($myFile);<br>
rename($tmpname, $myFile);<br><br>
//this will append text at the end of the file<br>
file_put_contents($myFile, "ajay", FILE_APPEND);
You can use fseek to change the pointer in the note.
It has to be noted that if you use fwrite it will erase the current content. So basically you have to read the whole file, use fseek, write your new content, write the old data of the file.
$file_data = file_get_contents('database.txt')
$fp = fopen('database.txt', 'a');
fseek($fp,0);
fwrite($fp, 'new content');
fwrite($fp, $file_data);
fclose($fp);
If your file is really huge and you don't want to use too much memory, you might want to have two file approach like
$fp_source = fopen('database.txt', 'r');
$fp_dest = fopen('database_temp.txt', 'w'); // better to generate a real temp filename
fwrite($fp_dest, 'new content');
while (!feof($fp_source)) {
$contents .= fread($fp_source, 8192);
fwrite($fp_dest, $contents);
}
fclose($fp_source);
fclose($fp_dest);
unlink('database.txt');
rename('database_temp.txt','database.txt');
The solution of Ben seems to be more straightforward in my honest opinion.
One last point: I don't know what you are stocking in database.txt but you might do the same more easily using a database server.
One line:
file_put_contents($file, $data."\r\n".file_get_contents($file));
Or:
file_put_contents($file, $data."\r\n --- SPLIT --- \r\n".file_get_contents($file));
This code remembers data from the beginning of the file to protect them from being overwritten. Next it rewrites the all the data existing in file chunk by chunk.
$data = "new stuff to insert at the beggining of the file";
$buffer_size = 10000;
$f = fopen("database.txt", "r+");
$old_data_size = strlen($data);
$old_data = fread($f, $old_data_size);
while($old_data_size > 0) {
fseek($f, SEEK_CUR, -$old_data_size);
fwrite($f, $data);
$data = $old_data;
$old_data = fread($f, $buffer_size);
$old_data_size = strlen($data);
}
fclose($f);
There is no way to write to the beginning of a file like you think. This is I guess due to reason how OS and HDD are seeing the file. It has got a fixed start and expanding end. If you want to add something in the middle or beggining it requires some sliding. If it is a small file just read it all and do your manipulation and write back. But if not, and if you are always adding to the beginning just reverse line order, consider the end as beginning...
file_get_contents() and file_put_contents() use more memory than using the fopen(), fwrite(), and fclose() functions:
$fh = fopen($filename, 'a') or die("can't open file");
fwrite($fh, $fileNewContent);
fclose($fh);

Categories