Jump to content

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


Go to solution Solved by jcbones,

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.
  • Solution

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).

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.