Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing checkbox value on server side

For my home automation project (using a Raspberry Pi with an Apache server and a configuration webpage) I'm trying to save a checkbox's setting to a file on the server side, but I can't get it working in my situation. Using php with fopen() and fwrite() I can store any string into a text file, that's no problem. The issue is that the form uses POST and I can't seem to 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 ('remembering and retrieving' the setting);

2) the setting that was just set by the user is written to the file, which happens when the page loads (POST).

These actions seem to get in eachother's way because php is server side. If the page is refreshed or visited for the first time there's no problem, the problem exists in reloading the page after the form is submitted. It doesn't really matter which method or language I use to save the checkbox's setting on the server side.

Which method could do the trick?

like image 942
Jim Avatar asked Aug 22 '26 11:08

Jim


2 Answers

You can set the file by doing something like this, assuming that the file only contains the value 1 or 0 if the checkbox should be set or not (call this script when submitting the form):

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

This is to put the checkbox in right format on screen. Use this when displaying the checkbox form.

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

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

like image 88
pBuch Avatar answered Aug 24 '26 01:08

pBuch


Can you post the fopen(), fwrite() code? If you're sending a POST to that php page, then you can grab the message contained in your HTML element simliar to this:

<?php
$message = $_POST['textarea_value_name'];
...
like image 36
Boon Xiong Avatar answered Aug 24 '26 01:08

Boon Xiong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!