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?
Edit: With the accepted answer, everything was working as I expected, except on the first load of the page - the checkbox was selected but the value printed out in code was null. I got it working with this:
index.php:
<?php session_start(); $_SESSION['submit'] = $_POST['submit'] ?? null; $_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(); $foo = ((!isset($_SESSION['submit']) && $_SESSION['foo'] != 'off') || ($_SESSION['foo'] === 'on')) ? true : false; echo 'foo='.$foo.'<br>'; ?>