Charlie
Charlie

Reputation: 11777

Save value of input to textfile on submit?

I'm working on a website for fun where the user enters something into two <input> elements in a form, presses submit, and then the text is logged to a .txt file, then the user is sent to a page for confirmation.

Is this possible to do with a form, and does it require javascript?

The basic structure of something like this would be:

<form method="post" action="">
<input type="text" />
<input type="text" />
<button type="submit"></button>
</form>

Upvotes: 2

Views: 4424

Answers (1)

stewe
stewe

Reputation: 42642

Thats possible without javascript.

You need to give each input a name and replace button with input.

Here is a start:

<?php
    if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
        $txt=$_POST['field1'].' - '.$_POST['field2']; 
        file_put_contents('test.log',$txt."\n",FILE_APPEND|LOCK_EX); // log to test.log (make sure that file is writable (permissions))
        header('Location: http://www.google.com/search?q='.$txt); // google as example (use your confirmation page here)
        exit();
    }

?>

<form method="post" action="">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" >
</form>

You can use $_POST['field1'] and $_POST['field2'] to get the values and log them.

FILE_APPEND is used to add new content to the end of the file instead of overwriting it.

LOCK_EX is used to aquire a write lock for the file (in case multiple users post at the same time)

Upvotes: 2

Related Questions