0

I've been at this for a while and been through other options on stack but can't get this to work. (I'm pretty nooby, sorry!)

I have a form which i want to send data to my txt file but it's just not writing.

ANY help greatly appreciated, thank you!!

My HTML Form:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>php test</title>
</head>

    <title></title>
</head>
<body>
        <form action="myprocessingscript.php" method="POST">
    <input name="field1" type="text" />
    <input name="field2" type="text" />
    <input type="submit" name="submit" value="Save Data">
</form>
    <a href='/tmp/mydata.txt'>Text file</a>
</body>

And my PHP

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
    $ret =  fwrite('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}
1
  • Do you get any errors? Commented Jan 23, 2018 at 21:29

2 Answers 2

1

You need to open a file before you can write to it with fwrite().

$fp = fopen('/tmp/mydata.txt', 'w');
$ret = fwrite($fp, $data);
//and don't forget to close it
fclose($fp);
if($ret === false) { 
   ...

Based on the flags you use in the question I think the function you might be thinking of is file_put_contents (See Docs HERE) and not fwrite.

Sign up to request clarification or add additional context in comments.

Comments

0

Try to add this line of code:

$myfile = fopen("/tmp/mydata.txt", "w") or die("Unable to open file!");

before the fwrite(), then you can now insert data/text in your file:

fwrite($myfile, $data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.