Save form inputs to a text file

I have the following form code on my webpage:

Can somebody please give me a changed version of this code so that:
– when the PUBLISH THIS POST BUTTON is clicked
– a file is written into a folder called ‘a’ which is 2 levels higher than the folder containing this file
– the file contains the values in:
select id=“category”
input id=“title”
input id=“subtitle”
select id=“status”
– with each value being preceded and followed by text such as “TEXT-HERE”
for example: TEXT-HERECategory 1TEXT-HERE
– after which (if successful) the user is taken to a file called “success.php”

    <form>
    <div class="w3-container pnc-label" style="font-size:.85em;"><label for="category"><b>(1) <i>Choose</i> Category:</b></label><br>
    <select name="category" id="category">
      <option value="cat1">&nbsp;Name of Category 1&nbsp;</option>
      <option value="cat2">&nbsp;Name of Category 2&nbsp;</option>
      <option value="cat3">&nbsp;Name of Category 3&nbsp;</option>
    </select>
</div>               

    <div><input id="title" name="title"  type="text" style="width:65%;margin-left:1em;background: #fff;padding-left:.4em;" 
    placeholder="click and type here A TITLE...this message will then disappear">
    </div>

    <div><input id="subtitle" name="subtitle" type="text" style="margin-left:1em;background: #fff;padding-left:.4em;" 
          placeholder="A Subtitle or Teaser or Date etc (optional)">
        </div>

    <!-- STATUS DROP-DOWN MENU  -->
    <label style="font-size:1em;text-align:left;margin:.8em 0 0 1em;line-height:1.2em;" for="status"><b>&nbsp; Choose Status:</b></label>
    <select name="status" id="status">
      <option value="PY">&nbsp;Published&nbsp;</option>
      <option value="PD">&nbsp;Draft&nbsp;</option>
      <option value="PX">&nbsp;Deleted&nbsp;</option>
    </select>
    &nbsp;&nbsp;

    <div><button type="submit" ><b>PUBLISH&nbsp;THIS&nbsp;POST</b></button></div>
    </form>

Well, we can not “alter” any code that is not posted here. You show HTML code, but, no PHP code.
Therefore, we can not alter something we do not have.
But, with that said, here is the basics you would use in a PHP script to do what you require…

<?PHP
$text_data = "TEXT-HERE Category : " . $_POST["category"] . " TEXT-HERE" . "/r/n";
$text_data .= "TEXT-HERE Title : "  . $_POST["title"] . " TEXT-HERE" . "/r/n";
$text_data .= "TEXT-HERE Subtitle : " . $_POST["subtitle"] . " TEXT-HERE" . "/r/n";
$text_data .= "TEXT-HERE Status : " . $_POST["status"] . " TEXT-HERE" . "/r/n";
file_put_contents("../../a/YourFileNameHere.txt", $text_data);
header("success.php");
?>

This will normally be placed at the top of the page before any of the HTML code. Also, it will not work unless you set up the FORM to point to itself. < form action="" method=“post” > which will make it post to itself… This sample is not tested, just created off the top of my head. Is this for a school assignment?

Thanks ErnieAlex
I will try adding the PHP code you suggest ASAP and report back if it works for me.
No it’s not a school assignment. At 74 my school days are a long way behind me!
It is to add some functionality to a website idea I am trying to develop to see if it has any merit.
Thanks again.

Cool ! I only asked because we get a lot of school people here when they get stumped. And, we have to treat them as beginners.

This code is not very secure, just a sample to explain how to start. Normally, you would save data like this into a database not text files. Text files are not secure and are hard to search if needed. But, give it a try and ask further questions that is what we are here for… Good luck!

I have tried using the code you gave me, and it almost works but not quite!
(1) I have changed the /r/n in your code to \r\n as otherwise it appears as text not ‘newline’
(2) The file is written, but none of the 4 values of ‘category’ ‘title’ ‘subtitle’ ‘status’ appear in the file.
The file instead contains:
TEXT-HERE Category : TEXT-HERE
TEXT-HERE Title : TEXT-HERE
TEXT-HERE Subtitle : TEXT-HERE
TEXT-HERE Status : TEXT-HERE
(3) after the file is written, the user is not taken to the ‘success.php’ file I have created in the same folder as this file. Instead, they remain on the page with the form, although all input is cleared.

Sorry, I typed it quickly and had the slashes backwards… Getting old, memory going… LOL

So, two things… You did save the file as a PHP file not HTML, correct? Also, did you fix the < FORM > tag to point to itself and you might need to alter the PHP code to check for the submit button. Do you know how to DEBUG this? You can check the inputs from the posted form if needed. Something like this would work:

<?PHP
die("<pre>".print_r($_POST,1)."</pre>");
?>

This should show you all of the posted fields from your < form >. If there is data in there, you can see what was actually sent to you and adjust your code as needed. Or, you can create a test file and post it here and we can help you solve where it is failing. But, it appears most of it is working. It seems you are just not getting the data sent back from the form.

Which file did you mean I should put this code into?
I put it into the page with the form, and also into the YourFileNameHere.txt file (which I renamed to end .php)
In both cases, the result is:
Array
(
)
If you want to look at my file in action it is live at:
https://personality.co.uk/psf1/M/usercode1/admin/createx.php

So, your sample page shows it is a PHP file. That is fine.
Next, in that page near the top use the code I posted and verify if you are getting data from the form. This should be after just above the < body > tag because you are not checking if the form is actually posted. Loosely, something like this:

<?PHP
die("<pre>".print_r($_POST,1)."</pre>");
$text_data = "TEXT-HERE Category : " . $_POST["category"] . " TEXT-HERE" . "\r\n";
$text_data .= "TEXT-HERE Title : "  . $_POST["title"] . " TEXT-HERE" . "\r\n";
$text_data .= "TEXT-HERE Subtitle : " . $_POST["subtitle"] . " TEXT-HERE" . "\r\n";
$text_data .= "TEXT-HERE Status : " . $_POST["status"] . " TEXT-HERE" . "\r\n";
file_put_contents("../../a/YourFileNameHere.txt", $text_data);
header("success.php");
?>

Instead of creating the file, it will stop and show you what is inside your form’s posted data!
Review it and see if you are actually getting the data in your form.

BEFORE YOU DO THAT! I reviewed your live site you posted. You have two bad lines of code on it.
To verify this, go to your page, RIGHT-CLICK on a blank area and select VIEW-SOURCE-PAGE and you will see the HTML code after the PHP is done creating it. You will see that it has two bad errors on the page. The first one is that you are sending code out before the HTML page. It is a < style > tag and it should be inside your < head > tags. The other is a missing < /div > tag just after the container tag.
Fix these FIRST. This might be causing the FORM to fail. Hope this helps…
(One other comment, you code uses more than one form and you do not test which form is being submitted, so that might be another issue at some point. )

Thanks ErnieAlex. Could you kindly look at my page now to see if I fixed the 2 problems you mentioned?
(1) the file is still being written without any field values in it, but I notice that after clicking the SUBMIT button, the page reloads with the following URL: https://personality.co.uk/psf1/M/usercode1/admin/createx.php?category=_c1&title=&subtitle=&status=_PY
– those are the 2 inputs I wanted written to file!
– I also wanted the 2 selects to be written to file
(2) you say I have 2 forms on my page, but if I search for ‘form’ in my source code, only Line 23 (<form action="" method=“POST”>) and Line 90 (</form>) are found. Where is the 2nd form?

Well, did you view the source of the new version? On line #50, you have a bad DIV.
Notice at the end of it you have an incorrectly placed semi-colon. like ";> Remove it.
Then, try and see if it works.

ALSO, around line 127, you have a < span > tag, but, you never END that tag. < /span >
Therefore, another errors.

Lastly, you have two forms on this page. One opens, then, closes and then another closes.
You are missing the second open for the form. Therefore, nothing would ever be posted.
( Third thing to fix . ) Should work after you fix these three errors.

OK, I fixed the ";> I can now see the URL on reload is:
https://personality.co.uk/psf1/M/usercode1/admin/createx.php?category=_c1&title=tttt&subtitle=ssss&status=_PY
which is including all 4 of the values I want written.
But they’re not in the file that is written.

Also, some code I have got from a google search which I put at the end of the file as follows:
<?php echo “TEST CODE”;
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
// collect value of input field
$name = $_REQUEST[‘status’];
echo "THIS IS STATUS VALUE ";
echo $name;}
?>
only shows TEST CODE but not THIS IS STATUS VALUE or the value in status!

So, you don’t want to fix it? You just want to add some random code at the end of the file?

DID you read the other post with the other two errors in it?

Also, this area:

<b>(2) GIVE YOUR POST A TITLE <i></b>

Opens a < b > tag and opens a < i > tag and closes a < b > tag… That is wrong, too !

You ask “DID you read the other post”. The answer is, I didn’t see it, only now that I look back can I see it. Maybe my age, or maybe I started answering the one before and didn’t see the 2nd one arrive!
I think I have fixed all the errors you have pointed out.
I have also deleted the random code you referred to – that wasn’t intended to fix anything, just to help understand what was going on. Anyway, it’s now removed, so is moot.
The main thing is I cannot find the “unopened 3rd /form” you refer to.
I have copied the source code into a text editor, and searching for the word “form” only shows one <form> (<form action="" method=“POST”>) and one </form> at the end of the file, just before </body></html>

Can you tell me what is the code which immediately follows the "unopened 3rd </form>" to help me find it?
PS It is now 0:36am in the UK, so I will look for your answer tomorrow morning.
Thank you again. Philip

Well, the extra form tag is now gone. But, you still have an error on your page.
RIGHT-CLICK on it, select VIEW-SOURCE and you will see the results AFTER the PHP had rendered the page and sent it to the browser. ( You will NOT see any PHP code there of course! )

Now, if you look at the page this way, you will see that there is still an extra semi-colon on one DIV line.
( At about line #50. ) Fix that and then let us know if it is working. If not, I will explain how to send me the file as a personal message so that I can review the live page instead of parts of it.

Also, what editor are you using? It does not indent lines very good and it is hard to read your code.
There are lots of editors out there. I use Netbeans which is free and shows up errors right away…

I believe I have now fixed the extra semi-colon, but the file is still being saved without any content except the text, so please tell me how to send you the file.

Regarding the editor, I am on MacOS (13.3) using BBEdit. I will investigate using “better” editor/IDEs such as NetBeans.

The reason you have no $_POST data is because you copy/pasted the following line, which wasn’t posted as code, so you ended up with some smart-curly quotes, which have no special meaning in a browser -

Delete and re-type the smart-curly quotes as straight ascii quotes and an empty action="" attribute is not valid html5. To get a form to submit to the same page using valid html5, leave the entire action attribute out of the form tag.

Good catch PHDR !

And, Stowman, all the other errors are gone now. Show fix what PHDR mentioned and let us know if it works. PHPstorm and Netbeans are two good editors to look at. I use Netbeans and am happy with it. Others here like PHPstorm, too. Netbeans is free.

That fixed it. I replaced the curly quotes and now the save works.
The only part of the code that didn’t work is the redirect to a file called ‘success.php’ when the Submit is completed.
I discovered in StackOveflow that header() redirects don’t work above PHP5.6, and I am using PHP7.2
I replaced it with echo '<script>window.location = "success.php";</script>';
and now it works.

Sponsor our Newsletter | Privacy Policy | Terms of Service