Using PHP and sessions, how can I check a checkbox the first time the page is loaded?
Here is a minimal sample of my code:
index.php:
<?php
session_start();
$_SESSION['foo'] = $_POST['foo'];
?>
<!doctype html>
<html>
<body>
<form method='POST'>
<input type="checkbox" id="checkFoo" name="foo" <?php echo (isset($_POST['foo']) && $_POST['foo'] === 'on') ? 'checked' : ''; ?>>
<label for="checkFoo">checkbox</label>
<button type="submit">Submit</button>
</form>
<?php include 'print.php'; ?>
</body>
</html>
print.php:
<?php
session_start();
echo $_SESSION['foo'].' ';
?>
Apart from the default value, this code works exactly as I intend:
- When the user checks the checkbox and clicks submit, it prints 'on'
- When the user unchecks the checkbox and clicks submit, it prints nothing
- Clicking the submit button does not change the value of the checkbox
How can I change the default (startup) value of the checkbox to 'on', without changing the above behavior?
CodePudding user response:
When the page will be first loaded, the $_POST['submit']
would not be set as the page would be accessed using a GET
Request.
So Modify the files:
index.php
<?php
session_start();
$_SESSION['foo'] = $_POST['foo'] ?? '';
?>
<!doctype html>
<html>
<body>
<form method='POST'>
<input type="checkbox" id="checkFoo" value="on" name="foo" <?php echo ((!isset($_POST['submit']) && $_SESSION['foo'] != 'off') || ($_SESSION['foo'] === 'on')) ? 'checked' : ''; ?>>
<label for="checkFoo">checkbox</label>
<button type="submit" name="submit">Submit</button>
</form>
<?php include 'print.php'; ?>
</body>
</html>
print.php
<?php
if(!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['foo'])) {
echo $_SESSION['foo'].' ';
}
?>
CodePudding user response:
This is a little verbose, but it's good practice to use a default value, then check if something exists before setting a variable to it.
Something like this should work.
<?php
session_start();
// default value is on
$foo = "on";
// if session has a value, use it instead
if(isset($_SESSION["foo"])){
$foo = $_SESSION["foo"];
}
// if post has a value, use it instead and set the session value
if(isset($_POST["foo"])){
$foo = $_POST["foo"];
$_SESSION["foo"] = $_POST["foo"];
}
$checked = $foo === "on";
This can be simplified in newer PHP versions (7 )
<?php
session_start();
$foo = $_POST["foo"] ?? $_SESSION["foo"] ?? "on";
$_SESSION["foo"] = $foo;