Write and Read Checkbox status to/of file with php - php

I am trying to save the status of my checkbox whether it is true or false (checked/unchecked) to a file. I managed to write the checkbox value to a file but I have no idea if this is even the right way to do it and I also don't know how to load it again.
I want that my checkbox status of the last time is "remembered" by reloading the page.
Using local storage isn't a option for me sadly.....
here my code:
<form action="database.php" method="post">
<input type="hidden" name="check2" value="0" />
<input type="checkbox" name="check2" value="1" />
<input type="submit" value="senden" />
</form>
<?php
$handle = fopen("saver.json", "a");
$fh = fopen( 'saver.json', 'w' );
fclose($fh);
foreach($_POST as $value) {
fwrite ($handle, $value);
}
fclose($handle);
?>
so this first deletes the old saved value and then writes a 1 or a 0 in the file.
Am I on a good way or do I think too simple?
All help is highly apprecciated !
Thanks a lot

Try this solution, all checkbox status are preserved after submit, reload and even restart your browser:
<?php
// Use SESSION to store checkbox status data. SESSION seems to have a lifetime, that will erase itself if exceed.
// If you need preserve status after browser closed (), you might need to consider storing them into a file.
session_start();
$sessionTgt = NULL;
// You probaby won't need this, but if you have corrupted session
// , use "localhost://my/url/thisScript.php?reset=1" to reset/erase this session key ("saveCheckBox").
if ($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["reset"]) && $_GET["reset"] === "1" ) {
unset($_SESSION["saveCheckBox"]);
echo("Ok, have just reset \$_SESSION[\"saveCheckBox\"]:");
exit();
}
// Reset this session key ("saveCheckBox") if it was not set.
if (!isset($_SESSION["saveCheckBox"])) {
$_SESSION["saveCheckBox"] = [
// "0" means server tell client no redirect. "1" means redirect immediately.
"ifRedirect" => "0",
// Store checkbox checked status. Example data will look like this:
// [
// "ckBox1" => "checked",
// "ckBox4" => "checked"
// ]
// , it means checkbox "ckBox1" and "ckBox4" are checked, others are not.
"checkBoxData" => [],
];
}
// Passing "reference", not value, to variable $sessionTgt.
$sessionTgt = &$_SESSION["saveCheckBox"];
// Print html form, by some condition. if some of the checkbox have "checked" status
// , then append the string "checked" inside their html <input> tag
// , so the input box will displayed as "checked".
function printFormAndCheckStatus ($checkStatus = NULL) {
echo(
'<form action="" method="post">' .
'<input type="checkbox" name="ckBox1" value="checked" ' . printCheckedMaybe("ckBox1", $checkStatus) . ' />' .
'<input type="checkbox" name="ckBox2" value="checked" ' . printCheckedMaybe("ckBox2", $checkStatus) . ' />' .
'<input type="checkbox" name="ckBox3" value="checked" ' . printCheckedMaybe("ckBox3", $checkStatus) . ' />' .
'<input type="checkbox" name="ckBox4" value="checked" ' . printCheckedMaybe("ckBox4", $checkStatus) . ' />' .
'<input type="submit" value="Submit" />' .
'</form>'
);
}
function printCheckedMaybe ($nameAttribute, $checkStatus) {
if (isset($checkStatus[$nameAttribute])) {
return "checked";
} else {
return "";
}
}
// POST "bouncing" logic. Notice the sequence is like this:
// -> Client get new page (client)
// -> Client user checked checkbox and post (client)
// -> Server save post data to SESSION (server)
// -> Server ask client for redirect (server)
// -> Client redirect immediately without doing anything (client)
// -> Server give back modified form content, that some input box has "checked" string
// appended inside the tag (client).
// The reason using double request instead of one, is to PREVENT POST DATA GET POSTED TWICE, which confuse server.
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$sessionTgt["ifRedirect"] = "1";
$sessionTgt["checkBoxData"] = [];
if (isset($_POST)) {
foreach ($_POST as $name => $value) {
$sessionTgt["checkBoxData"][$name] = $value;
}
}
header("Refresh:0");
// When client get this response header pattern/content, client (browser) know he need to
// refresh the page immediately (request the same url again).
} else {
if ($sessionTgt["ifRedirect"] !== "1") {
if (isset($sessionTgt["checkBoxData"])) {
printFormAndCheckStatus($sessionTgt["checkBoxData"]);
} else {
printFormAndCheckStatus();
}
} else {
// Just after redirect.
$sessionTgt["ifRedirect"] = "0";
printFormAndCheckStatus($sessionTgt["checkBoxData"]);
}
}
Does this solve your problem? This solution save your checkbox status inside server SESSION, but SESSION seems to have a lifetime, that will erase itself if exceed. (maybe I'm wrong). If you need long term storing you can write it into a file or database.

Related

Handling PHP POST variable from other php file and managing $_SERVER["PHP_SELF"]

I stucked at a problem I can't figure out why isn't is working.
I am handling POST variable from another php file:
$temp_variable = $_POST['activity'];
After my code process $temp_variable, I try to make a button (still in the same php file where I handled $_POST['activity'])
echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="submit" value="OK" name="process_more"/>';
echo '</form>';
Then I try to catch OK button press, to start another activity:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$query = "DELETE FROM table1 WHERE id = 5";
mysqli_query($conn,$query)
}
My problem is that the "Delete FROM" part of the code executes immediately, before the user press the "OK" button.
What can be the problem ?
Check something more specific to your form.
if(isset($_POST['process_more'])){
if ($_POST['process_more'] == 'OK') {
// execute the delete
}
}
$_SERVER["REQUEST_METHOD"] could equal 'POST' from a different form submission..

How to submit form without moving to next page in PHP

The Problem
I am trying to submit a form in php but due to the nature of what i want i need the page to not go onto the next one i just want it to submit the data and refresh the current page or whatever, at current it submits the data and goes onto page 2 which i dont want i just need it to submit the data and stay on the current page, if thats possible!
The Code
//page 1 code
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form method="post" action="jacob_dailey.php">
<select name="baby_status">
<option value="playing">Playing</option>
<option value="awake">Awake</option>
<option value="sleeping">Sleeping</option>
</select>
<br />
<input type="submit" value="Submit"/>
</form>
</center>
//page 2 code
<?php
if (isset($_POST['baby_status'])) {
$baby = $_POST['baby_status'];
setcookie("baby_status", $baby, time() + 31556926, '/'); // Data will Store For 1 Year
header('Location: ' . $_SERVER['PHP_SELF']);
}
$status = $_COOKIE['baby_status'];
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
echo '</center>';
?>
Page 2 code shouldnt be as important but i just need it so when i click submit on page 1 it updates the information on page 2 but doesnt take me to page 2.
Cheers!
Your form can submit onto itself. Just in the action="xyz" either leave it (the whole action=... attribute) out entirely or else name the page that also contains the form there between quotes.
Then when you load the page you check the $_POST or $_GET array (depending on the method) to see if the submit button was pushed or if someone just navigated to the page. (You'll want to give you submit button a name="foo".)
action="jacob_dailey.php" in your form takes you to that page, you either paste your php code to main page and replace action with just "" or you will search AJAX and learn how to it with that
You can use jQuery.ajax(). Example here:
http://www.formget.com/form-submission-using-ajax-php-and-javascript/
This example uses a database, but you can use a php file to return values and read them from the response in javascript. Do not put any action to the form but enable a click event handler on the submit button to enable the function.
Also my example here: http://dev.ossipesonen.fi/alkoholilaskuri/
A very simple form where you insert values, pass them onto PHP with $_POST and then calculates the right amounts and sums, and you print them in the response.
Solution: Update Status Without Page Reload Using XHR and Filesystem Storage
If you want someone on another computer to see the update, then you'll need to store that information on the server. You could store the information in a database, but for this small bit of information I'm using the filesystem.
page1.php
<?php
// get baby status if available
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
// prepare to update select list
list($pl_check, $pl_check, $pl_check) = array('', '', '');
switch ( $status ) {
case 'playing': $pl_check = ' selected '; break;
case 'awake': $aw_check = ' selected '; break;
case 'sleeping': $sl_check = ' selected '; break;
}
?>
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form id="baby_form" method="post" action="update_baby.php">
<select id="baby_status" name="baby_status">
<option value="playing" <?php echo $pl_check ?>>Playing</option>
<option value="awake" <?php echo $aw_check ?>>Awake</option>
<option value="sleeping"<?php echo $sl_check ?>>Sleeping</option>
</select><br />
<input type="submit" value="Submit"/>
</form>
See Baby Status
</center>
<script>
// XHR/PHP/Filesystem method
function update_baby () {
var baby_status = document.getElementById('baby_status');
var status=encodeURIComponent(baby_status.options[baby_status.selectedIndex].value)
var parameters = 'baby_status=' + status
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('POST', 'update_baby.php', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
console.log(this.responseText)
alert(this.responseText)
}
xhr.send(parameters)
}
// hook up baby status function to form submit
document.getElementById('baby_form').addEventListener('submit', function(evt){
evt.preventDefault()
update_baby()
})
</script>
page2.php
<?php
// execute baby update code and get current status
include 'update_baby.php';
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
?>
<br>
Update Baby Status
</center>
update_baby.php
<?php
if (isset($_POST['baby_status'])) {
$status = $_POST['baby_status'];
// prepare php script text for baby status file
$status_write = <<<EOT
<?php
\$status = '$status';
?>
EOT;
// write status to baby_status.php
if ( $baby_status_file = fopen('baby_status.php', 'w') ) {
fwrite($baby_status_file, $status_write);
fclose($baby_status_file);
}
echo 'Baby status updated.';
}
else {
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
}
?>
Note: To use this option the directory these files are in must be writeable by the web server.

session variable changes unexpectedly on page load in wordpress plugin

I have a problem with SESSIONs in wordpress. I have looked around but could not find any answer. A similar question has been asked in another post on stackaoverflow, but no answer yet.
I have followed this tutorial to build my own FORM:build your own wordpress contact form in 5 minutes.
The problem
To make my form more secure, I decided to generate a session string, and store this string in a SESSION global array (to prevent form hijacking). I send this same string as hidden field when the form is posted. And than I compare this 2 values. However, it seems to me that when the form is submitted, the SESSION is not the same as the one i stored in the SESSION array before submission.
function myfunction() {
ob_start();
$errors = array();
//deliver_mail();
if(isset( $_POST['cf-submitted'] ) ) {
if( $_POST['formtoken1'] !== $_SESSION['formtoken1'] ) {
$errors['token'] = '<div>The form submited is not valid.</div>';
//debug
echo $_SESSION['formtoken1'];//At this point, SESSION[formtoken1] should be same as the one we generated before FORM submit, but it is not!
}
if(empty($errors)) {
//No Errors! Send Email
}
}
$_SESSION['formtoken1'] = md5(uniqid(rand(), true));
$_SESSION['formtoken1'] = htmlspecialchars($_SESSION['formtoken1']);
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<input type="text" name="formtoken1" id="formtoken1" value="'. (isset($_SESSION['formtoken1']) ? $_SESSION['formtoken1'] : '') . '" />';
echo '<p><input type="submit" name="cf-submitted" value="Send"></p>';
echo '</form>';
return ob_get_clean();
}
add_shortcode( 'my_contact_form', 'myfunction' );//Create shortcode
When this form is submitted, it always creates error because SESSION variable is not same as the POST variable. When I test this same code outside wordpress on my local xampp server, it works. I will be greatful if anyone can help me. I have also tried session_start() at top of script, but still the same problem.
After some trials, I realized that the post title was displaying on top of the page. I was starting ob_start() inside myfunction(). So, title was outputting before SESSION was started. I changed the code as below, and it works for now. The only problem with this solution is that wordpress is calling ob_start() at every page load. it would be better if it worked inside the myfunction() because it would mean ob_start() is executed only when the short-code is called within a post.
`
//Plugin Name: test form
ob_start(); //put this outside the myfunction()
if(!session_id() ) {
session_start();
}
function myfunction() {
$errors = array();
//deliver_mail();
if(isset( $_POST['cf-submitted'] ) ) {
if( $_POST['formtoken1'] !== $_SESSION['formtoken1'] ) {
$errors['token'] = '<div>The form submited is not valid.</div>';
//debug
echo $_SESSION['formtoken1'];//At this point, SESSION[formtoken1] should be same as the one we generated before FORM submit, but it is not!
}
if(empty($errors)) {
//No Errors! Send Email
}
}
$_SESSION['formtoken1'] = md5(uniqid(rand(), true));
$_SESSION['formtoken1'] = htmlspecialchars($_SESSION['formtoken1']);
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<input type="text" name="formtoken1" id="formtoken1" value="'. (isset($_SESSION['formtoken1']) ? $_SESSION['formtoken1'] : '') . '" />';
echo '<p><input type="submit" name="cf-submitted" value="Send"></p>';
echo '</form>';
return ob_get_clean();
}
add_shortcode( 'my_contact_form', 'myfunction' );//Create shortcode`

PHP, display message if one or more fields is empty

What I want is to show the error (message), only if the user do a false action. For example, if the field is empty, it will show (Please fill all the fields). I've already done that, but the problem that I have is that it shows also if the user enter to the page for the first time, meaning it does NOT respects the (if condition) that I have written !
The question :
How to show the message only if one of the fields is empty ?
Any ideas on how I can solve it ?
Here is my code :
<?
$conn = mysqli_connect('localhost', 'db', 'db_pass', 'db_name') or die("Error " . mysqli_error($conn));
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$old_password = trim($_POST['old_pass']);
$new_password = trim($_POST['new_pass']);
$email = mysqli_real_escape_string($conn,$email);
$old_password = mysqli_real_escape_string($conn,$old_password);
$new_password = mysqli_real_escape_string($conn,$new_password);
if(empty($email) || empty($old_password) || empty($new_password)){
echo 'Please fill all the fields !<br>';
}
else{
$sql="UPDATE users SET pass='$new_password' WHERE email='$email' AND pass='$old_password'" or die("Error " . mysqli_error($conn));
$result = mysqli_query($conn,$sql);
mysqli_close($conn);
}
if($result){
echo'Password changed successfully !';
}
elseif(!$result) {
echo 'The email/password you provided is false !';
}
?>
Validation of any form happens in the "action" file within a condition i.e. the validation should be subjected to the event of user clicking the submit button. For this to work you should check that
1. Your form has a submit button with a name property set to say submit (can be anything)
eg: <input type="submit" name="submit" id="someid" value="Submit" />
2. The form must have action property pointing to a processor file
eg: <form action = "somefile.php" method = "post">
3. In the somefile.php file the validation code must be within a condition which checks for the event of form been submited
eg://somefile.php
<?php
if(isset($_POST['submit']{
//all the validation code goes here
}else{
//for a single page form and validation
// the code for displaying the form can go here
?>
I suggest you to do this:
First define a variable with plain $_POST[] for eg $name = $_POST['name'];
Then, check if all the vatiables you've define are empty or not.
Lastly, Use escape_string() or whatever you want.
The solution is to check for a variable that you know will always be set if the form is submitted, usually the submit button.
For example, if your form ends like this:
...
<input type="submit" name="change_password" value="Change password" />
</form>
then in the PHP code you could check
if(isset($_POST['change_password'])) {
// The submit button was in the POSTed data, so this is a form submit
} else {
// This is a new page load
}
Alternatively, if you are POSTing the data, you can check which HTTP method was used to call the form:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Form was posted
} else {
// $_SERVER['REQUEST_METHOD'] == 'GET'
}
The pattern I commonly use is:
$showForm = true;
if( is_form_postback() ) {
if( data_is_valid() ) {
redirect_to_thank_you_page();
} else {
show_validation_errors();
$showForm = false;
}
}
if($showForm) {
// Print the form, making sure to set the value of each input to the $_POSTed value when available.
}

PHP Form must be submitted twice to update checkbox

I'm still relatively new to PHP. I'm trying to build a privacy settings page for members to opt out of automatic emails for triggered events (i.e. private message notification). I want the checkbox set automatically based on the database setting. As of now, the form does update the database correctly, but the checkbox status does not show the correct setting unless the Submit button is pressed twice, or the page is reloaded. Setting would be '0' for unchecked, '1' for checked. I'd love to use Ajax or jQuery to handle this, but I don't know those at all.
privacysettings.php
<?php
$id = "";
$pm_mail_able = "";
$pm_email = "";
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
//query to get checkbox status
$sql = mysql_query("SELECT * FROM members WHERE id='$id'");
while($row = mysql_fetch_array($sql)){
$pm_mail_able = $row['pm_mail_able'];
}
switch ($pm_mail_able) {
case 0:
$pm_setting = NULL;
break;
case 1:
$pm_setting = "checked=\"checked\"";
break;
}
if(isset($_GET['pm_email']) && !empty($_GET['pm_email'])) {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='1' WHERE id='$id'");
} else {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='0' WHERE id='$id'");
}
?>
<html>
Email Notifications<br />
<form name="testform" method="get" action="PvResult.php">
When a friend sends me a private message
<input type="checkbox" name="pm_email" value="on"<?php echo $pm_setting;?> />
<br /><br />
<input type="submit" value="Submit" />
</form>
</html>
PvResult.php
<?php
$url = 'http://www.mywebsite.com';
//If the form isn't submitted, redirect to the form
if(!isset($_GET['Submit']))
header('Location: '.$url.'/privacysettings.php');
//Redirect to the correct location based on form input
$pm_email = $_GET['pm_email'];
$url .= '/privacysettings.php?pm_email='.$pm_email;
header('Location: '.$url);
?>
Okay, hopefully this won't just answer your question, but give you a few best practices you might want to consider.
You can combine these two scripts into one relatively easily. Also, I'd highly suggest using a POST instead of GET; GET is very limited and is not intended to submit data like you're using it. If you're going to be changing data in a back-end store, using GET will bite you. Maybe not today, maybe not tomorrow, but it will, trust me.
You really should consider moving to PDO instead of the mysql_ functions. PDO is a lot better in handling parameterized queries, which you really should have here for better security, and it's more portable if someday you want to move to a different database system.
I'm still a little hazy on how your app is getting the $id. Most apps get it from a $_SESSION variable, making sure that the user has successfully validated a login. If you're not doing that, please do. You might want to thoroughly digest this article, it's got a lot of juicy best practices regarding authentication and "remember me"-type functionality.
Here's a bit of a rewrite. I haven't actually tested it, but it should give you a pretty good idea on where to go with your immediate needs. If it throws any errors (remember the disclaimer: I haven't actually tested it!), let me know and I'll try to debug it.
<?php
$message = '';
$pm_setting = '';
$id = 0;
// Put your $id retrieval logic here. It should look something like:
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
if (!preg_match('/^\\d{1,10}$/', $id) > 0) {
// Someone is trying to hack your site.
header("location: scum.php");
exit();
}
$id = intval($id);
}
// Quick security note: You might want to read up on a topic called
// session hijacking if you want to ensure your site is secure and
// this $id isn't spoofed.
if (isset($_POST['Submit'])) {
// The form is being submitted. We don't need to read the current
// pm_mail_able setting from the database because we're going to
// overwrite it anyway.
if ($id > 0) {
$pm_mail_able = 0;
if (isset($_POST['pm_email']) && $_POST['pm_email'] === 'on') {
$pm_mail_able = 1;
$pm_setting = 'checked ';
}
$query = 'UPDATE members SET pm_mail_able='.$pm_mail_able.
' WHERE id = '.$id;
mysql_query($query);
// Another quick security note: You REALLY need to consider
// updating to PDO so that you can bind these parameters
// instead. The mysql_ functions are probably going to be
// deprecated soon anyway.
if (mysql_affected_rows($query) > 0)
$message = '<p style="color: #00a000;">Settings saved!</p>';
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else {
// This is the first load of the form, we need to just display it
// with the existing setting.
if ($id > 0) {
$query = mysql_query('SELECT * FROM members WHERE id = '.$id);
if (($row = mysql_fetch_array($query, MYSQL_ASSOC)) !== FALSE)
if ($row['pm_mail_able'] === 1) $pm_setting = 'checked ';
}
}
?>
<html>
<body>
<?= $message ?>
<!-- Without action parameter, form submitted to this script. -->
<form name="testform" method="post">
E-mail notifications<br />
<input type="checkbox" name="pm_email" value="on" <?= $pm_setting ?>/>
When a friend sends me a private message
<br /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try to do these settings and see if it will work:
1) You need to add an space between "on" and "checked=checked"
<input type="checkbox" name="pm_email" value="on" <?php echo $pm_setting;?> />
2) You have to reference the submit button by its name, not its value
<input type="submit" name="Submit" value="Send" />
3) When the setting is "0", set $pm_setting as a empty string, instead of NULL
case 0:
$pm_setting = '';
4) Maybe there is some problem with $_GET['pm_email'] and the else is always being executed
5) If the things work when you press the Submit button twice, it means that the form is passing some GET var that make the code work, so try to discover what var is this

Categories