Server side storage of checkbox value

For my home automation project (using a Raspberry Pi with an Apache server and a web config page) I am trying to save a checkbox parameter to a file on the server side, but I cannot get it to work in my situation, Using php with fopen () and fwrite ( ), I can save any line in a text file, which is not a problem. The problem is that the form uses POST and I cannot figure out how to write my code in such a way that:

1) the checkbox itself is set to the value that is currently present in the text file ("memorize and retrieve" settings);

2) the parameter that was set by the user is written to the file, what happens when the page is loaded (POST).

These activities seem to fall into each other since php is server side. If the page is refreshed or visited for the first time, no problem, the problem is the page reload after the form is submitted. It doesn't really matter which method or language I use to keep the checkbox checked on the server side.

What method could do the trick?

+3


source to share


2 answers


You can install the file by doing something like this, assuming the file only contains 1 or 0 value if the checkbox is checked or not (call this script when the form is submitted):

if(isset($_POST["mycheckboxname"])){
   file_put_contents('file.txt', '1');
}
else{
   file_put_contents('file.txt', '0');
}

      

It needs to be checked in the right format on the screen. Use this when displaying the checkbox shape.



$checked = file_get_contents('file.txt');
echo '<input type="checkbox" name="mycheckboxname" ';
if($checked=='1') echo 'checked ';
echo '/>';

      

Make sure to set the correct permissions when creating the file so that the PHP processor has write access to it.

+2


source


Can you post the code for fopen (), fwrite ()? If you POST to this php page, you can capture the message contained in your HTML element like this:



<?php
$message = $_POST['textarea_value_name'];
...

      

+1


source







All Articles