Reputation: 161
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);
?>
Upvotes: 1
Views: 18492
Reputation: 26
The form's submit action is "get", but in your PHP code, you get the variable by $_POST. Try by $_GET instead.
Upvotes: 1
Reputation: 2777
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);
}
?>
Upvotes: 3
Reputation: 145492
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.
Upvotes: 1
Reputation: 69967
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.
Upvotes: 1
Reputation: 12566
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
.
Upvotes: 0