PHP how to clear memory when refreshing - php

I am facing the following issue. I have a simple textarea where user will use to submit text which is subsequently written to a text file in the server. This is working.
But when I refresh the page it adds in the last added text into the text file again causing duplicate entries.
Any idea what I must do to prevent this? Below is the code I used for the textarea portion.
<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>
</html>
<?php
if(isset($_POST['text_box'])) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."\r\n");
fclose($fh);
}
?>

Pages that are loaded via POST will cause the browser to ask the user to resubmit the information to view the page resulting in the actions performed by that page happening again. If the pages is requested via GET and has variables in the querystring the same thing happens but silently (without the user being prompted to d it again).
The best to work around this is to use the POST/REDIRECT/GET pattern. I used it in an example about processing payments that I wrote for Authorize.Net. Hopefully that points you in the right direction.

A simpler so
You can just store a simple hash on session and regenerate it every time.
When the user reloads the page the php wont be executed.
<?php
if(isset($_POST['text_box']) && $_SESSION['formFix'] == $_POST['fix']) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."\r\n");
fclose($fh);
}
?>
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<?php
$value = md5(rand(1,999999));
$_SESSION['formFix'] = $value;
?>
<input type="hidden" name="fix" value="<?= $value; ?>" />
<input type="submit" id="search-submit" value="submit" />
</form>
</body>
</html>
ps: the order of the blocks will matter, so you need to invert em.

As John said, you need to redirect user after form submit.
fclose($fh);
// and
header("Location: success.php or where else");
exit;
Note: Your redirection won't work unless ob_start is not called before, cos your page contains html outputs.
// form.php
<?php ob_start(); ?>
<html>
<body>
<? if (isset($_GET['success'])): ?>
Submit OK! New submit
<? else: ?>
<form name="form" method="post" action="form.php">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
</form>
<? endif; ?>
</body>
</html>
<?php
if(isset($_POST['text_box'])) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."\r\n");
fclose($fh);
// send user
header("Location: form.php?success=1");
exit;
}
?>

Related

How can I get the output for form without the page changing

I am trying to get information from textarea to be converted to a .py file.
Here's my file https://jsfiddle.net/girlwhocancode/68mb49gq/
<form action=action.php method="post">
<center>
<textarea placeholder="Code you want to execute in python..."></textarea>
</center><br/>
<center><input type="submit" class="button_example"></center>
</form>
and this is my php file:
<?php
$path = #PATH;
if (isset($_POST['field1'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
For some reason my php isn't working and I have no idea how to keep the same webpage after submitting
Try this:
<form action="action.php" method="post">
<center>
<textarea name="script" placeholder="Code you want to execute in python..."></textarea> //added name
</center><br/>
<center><input name="submit" type="submit" class="button_example"></center>
</form> // added name submit
in php
<?php
$path = #PATH;
if (isset($_POST['submit'])) {
$fh = fopen($path,"a+");
$string = $_POST['script'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
Remember that in php $_POST/$_GET keys are always your form field
names

How to upload input to a text file in php

I want to upload the contents written in the text box in a text file using php. But also they should only be written if the string contains a particular pattern.
here's my php code
<?php
$data = $_POST["text"];
public function copy(){
if (strpos($data, '123') !== false){
$myfile = "uploads/mydata.txt";
$fh = fopen($myfile, 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
}
}
?>
It says unexpected public on line 4.
and my form is:
<?php require_once('tally.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<form action="index.php" method="post">
Input the first record
<input type="text" name="text">
<input type="submit" name="submit" action="submit">
Submit
</submit>
</form>
</body>
</html>
Thanks for helping
why are you using fopen, just use file_put_contents.
The input name is text and in php you are trying to receive $_POST['data'].
Change name of input to data or change the php code and get $_POST['text'].
also your submit button is not xhtml or html5 standard compliant. change it to no need for closing tag or additional text.
I cannot see where are you calling the copy function.
code should be something like this.
<?php
$data = $_POST["data"];
if(!empty($data)) {
copy2($data);
}
function copy2($data){
if (strpos($data, '123') !== false){
$myfile = "uploads/mydata.txt";
$fh = fopen($myfile, 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
}
}
?>
HTML goes like this:
<?php require_once('tally.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<form action="index.php" method="post">
Input the first record
<input type="text" name="text">
<input type="submit" value="submit">
</form>
</body>
</html>
Remove the word public if this function is not in a class.
public function copy(){
becomes
function copy(){
There is not tag associated with data. Please add:
<input type="text" name="data">

HTML forms, fwrite and PHP

I want to use fwrite to save data into a .txt file. The action method seems to be working, as it can show HTML tags when being transfered when pressing submit, but i wont run the PHP.
<HTML lang="da">
<style>
</style>
<header>
<title>Tilføj</title>
<meta charset="ISO-8859-1">
</header>
<body>
<form method="post" action="eksamen_save_data.php" enctype='multipart/form-data'>
<fieldset>
<legend>Filmoplysninger</legend>
<div><label>Titel: <input type="text" name="titel" id="titel" required="required" size="60" maxlength="100"></label></div>
<div><label>Hovedskuespiller: <input type="text" name="hovedskuespiller" id="hovedskuespiller" required="required" size="30" maxlength="100"></label></div>
<div><label>Genre: <input type="text" name="genre" id="genre" required="required" size="60" maxlength="100"></label></div>
<div><label>Format: <input type="text" name="format" id="format" required="required" size="60" maxlength="100"></label></div>
<div><label>Billede: <input type="file" name="billede" id="billede" required="required"></label></div>
</fieldset>
<div><input type="submit" id="ok" value="OK"></div>
</form>
</body>
This sends it to the "eksamen_save_data.php" that looks like this:
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
//$Billede = $_FILES["billede"]["navn"];
//if($_FILES){
// move_uploaded_file($_FILES["billed"]["navn"], $_FILES["billed"]["navn"]);
//}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
$fh = fopen("data.txt", "a") or die("Fejl i åbning af fil!");
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
fclose($fh);
?>
If i write some HTML in the "eksamen_save_data.php" i can show this, but it wont run the PHP. I'm using XAMPP.
The problem is that it wont save to the "data.txt" file as i tell the PHP to do.
Another question; is there also a way, I can make the PHP run in the same file as where I have my fieldset?
LAST EDIT:
Most of the time it's the little mistakes that proves to be the biggest problem. For me i personally forgot to use: localhost/eksamen_tilføj.php in the browser.
So it was me making a mistake in XAMPP.
Use file_put_contents
file_put_contents("data.txt", $user_data, FILE_APPEND);
It does all the jobs like file open, write and close. Advantage is if the file does not exist then it will create.
Find full working code
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
$Billede = $_FILES["billede"]["name"];
// Example of accessing data for a newly uploaded file
$fileName = $_FILES["billede"]["name"];
$fileTmpLoc = $_FILES["billede"]["tmp_name"];
// Path and file name
$pathAndName = "upload/".$fileName;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if ($moveResult == true) {
echo "File has been moved from " . $fileTmpLoc . " to" . $pathAndName;
} else {
echo "ERROR: File not moved correctly";
}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
file_put_contents("data.txt", $user_data, FILE_APPEND);
?>
you'll have to remove the third parameter $test (because it specifies the length of the content to be written). But $test is not defined in your PHP file, so it won't write anything..
So change this
fwrite($fh, $user_data, $test) or die ("Fejl i skrivning til fil!");
into this
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
and have a look at this :)
As for your second question: sure you can merge your form and submit scripts:
<?php
if(count($_POST) > 0) { //
/** Form submit function, file write **/
} else {
?>
<html>
<form action="#" method="POST">
<!-- Enter HTMLform here -->
</form>
</html>
<?php } ?>
This pseudocode is not pretty, but will do in terms of explaining stuff. The # in the form action means that the same script is to be called upon submission. The if(count($_POST) > 0) checks whether data has been submitted. If so, the file will be written. Otherwise, the form will be displayed.
Good luck.

Write data from text box to a text file

I have developed a text box and I am trying to write this data to a text file.
The PHP code is generating the file but the data is not being written.
below is my code:
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
<?
$a=#$_POST["text_box"];
$myFile = "t.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh,$a);
fclose($fh);
?>
the biggest issue i see with your code is the fact that you aren't opening php tags. you do
<?
but it should be
<?php
then, the way you call $_POST and write file and stuff means it will be executed when you first load the form into the browser as well. the php engine makes no distinction between first run and consecutive run. this means that even if the user don't submit anything, there will still be an empty file, created from the run of the script where the form was displayed. it's a side effect. i've modified your code just a little. here's my take on 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>
</html>
<?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);
}
?>
The form's submit action is "get", but in your PHP code, you get the variable by $_POST. Try by $_GET instead.
The form is sending a GET request, but you are trying to access $_POST["text_box"]. Try changing that to $_GET['text_box'], or using a form method POST instead.
You can replace your PHP code with just:
if ($_REQUEST) {
file_put_contents("t.txt", $_REQUEST["text_box"]);
}
That will ensure that file only gets overwritten when the form is actually submitted, not also when the form is displayed.
Does $a have data? Try echo'ing it out. Or, try print_r'ing your $_POST.
EDIT: Your form's method is get, but you're trying to use $_POST. Use $_GET, or, $_REQUEST.

Button Click Counter in PHP

I'm trying to build a tiny skeleton framework for a friend, where each time a button is pressed a certain animation is played. He wants a way to count the number of times the button is clicked, as well, but I can't seem to get that part working. What am I doing wrong?
<?php
if( isset($_POST['mushu']) )
{
echo "Working.";
playAnimation();
clickInc();
}
function playAnimation()
{
/* ... */;
}
function clickInc()
{
$count = ("clickcount.txt");
$clicks = file($count);
$clicks[0]++;
$fp = fopen($count, "w") or die("Can't open file");
fputs($fp, "$clicks[0]");
fclose($fp);
echo $clicks[0];
}
?>
<html>
<head>
<title>Adobe Kitten</title>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="button"
value="Let's see what Mushu is up to."
name="mushu">
</form>
</body>
</html>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit"
value="Let's see what Mushu is up to."
name="mushu">
</form>
First of all use the form with method="post", or change $_POST[] to $_GET[] in your Script.
And If your Button is not a Submit button, then you are not submitting the form. So I've changed type="button" to type="submit".
Should work
The code looks fine, I tested it and it worked for me.
I suggest:
Make sure the file isn't read-only.
Make sure the file is called "clickcount.txt"
Make sure it's in the same folder as your script.
It would be helpful to know the error but a shot in the dark - it could be a problem with Write permissions?
also, change to:
<input type="submit" value="Let's see what Mushu is up to." name="mushu" />

Categories