I am trying to save the data entered in HTML form in a text file. I am using a php script to do this. When I click on submit button, it does not save the data in text file. Can someone tell me what is going wrong here.
Below is the code snippet -
HTML Form -
<form id="post" name="post" method="post" action="input.php">
Name: <input type="text" name="name"><br>
Text: <textarea rows="50" cols="85" name="blogentry"></textarea>
<input class="button" type="submit" value="Submit">
</form>
PHP - (input.php)
<html>
<head></head>
<body>
<?php
// variables from the form
$name = $_POST['name'];
$blogentry = $_POST['blogentry'];
// creating or opening the file in append mode
$dataFile = "data.txt";
$fh = fopen($dataFile, 'a');
// writing to the file
fwrite($fh, "Name - " . " " . $name . " " . "
");
fwrite($fh, "Blog - " . " " . $blogentry . " " . "
");
fclose($fh);
?>
</body>
</html>
In cases like this it's useful to pinpoint the problem. Maybe the form isn't submitting your textarea, or maybe your PHP isn't receiving it, or maybe it's some problem with what you're doing with the value.
If you view your form submission in an inspector like Firebug, do you see the contents of your textarea being submitted in the request?
If you do a var_dump($_POST)
in your code, do you see all the values being submitted from the form?
Can you try this,
if(isset($_POST['name']) && isset($_POST['blogentry'])){
$name = $_POST['name'];
$blogentry = $_POST['blogentry'];
// creating or opening the file in append mode
$dataFile = "data.txt"; // make sure the directory path is correct and permission of the folder
$fh = fopen($dataFile, 'w'); // writing to the file
$stringData = "Name - " . " " . $name . " " . "
";
$stringDataBlog = "Blog - " . " " . $blogentry . " " . "
";
fwrite($fh, $stringData);
fwrite($fh, $stringDataBlog);
fclose($fh);
}
There is no fault in your code. If data.txt is there and have the permission to write on it the code should work. Please check file permission.
I just ran into the same problem. You need to add the form tag with the form id to the textarea element. Correcting your code from above::
<form id="post" name="post" method="post" action="input.php">
Name: <input type="text" name="name"><br>
Text: <textarea rows="50" cols="85" name="blogentry" form="post"></textarea>
<input class="button" type="submit" value="Submit">
</form>
Then it should work.