Jump to content

Writing GET content (from form.php file) to a separate text.txt


sataiuto

Recommended Posts

How to do it? I have read some methods but they seem to not work. This is what  I have got so far:

 

 

<?php
$name= $_GET["name"];
$comment= $_GET["comment"];
$f = fopen('data.txt', 'a');
fwrite($f, "<p>$name and $comment</p><hr>");
fclose($f);
?>
 
So, basically I want to write certain data from the input form to a text file.
 
 
ATM, the server creates the data.txt but doesnt write anything on it. The $name and $comment variables are working if I echo on submit.
 
 
Any help is appreciated.

That code should work, as I see nothing systematically wrong with it.

file_put_contents() is easier, and less coding.

 

$name = trim($_GET['name']);
$comment = trim($_GET['comment']);
if(file_put_contents('data.txt',"<p>$name and $comment</p><hr />\n",FILE_APPEND) !== false) {
  echo 'File was written successfully!';
} else {
 echo 'The file failed to write.';
}

exactly file_put_contents is easier. And like jcbones showed you really have to show an error if the file was not written since there can be enough reasons that the function could fail.

 

One of the reasons is permisions on a linux server. Give your directory where you want to write to enough permissions (755).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.