简体   繁体   中英

PHP Radio buttons and Session

Ok, I have two radio buttons 'A' and 'B' and user have a choice to select anyone of them, by default button 'A' is selected but when user come to my website and selects 'B' then selection changes to button 'B' however the problem is,

when the user move to another page in my site the selection goes back to default ?? How to fix it ?? can it be done with the help of cache and session ? if yes then how :?

here is the buttons,

<form name="f1" method="POST" action="<?php echo $PHP_SELF;?>">
<span>Family filter:</span>
<ul>
<li><input type="radio" name="r1" value="o" onClick="submit();" <?php echo ($_SESSION['r1'] == "o") ? 'checked="checked"' : ''; ?><?php echo ($_POST['r1'] == 'o' ) ? 'checked="checked"' : ''; ?> />On</li>
<li><input type="radio" name="r1" value="p" onClick="submit();" <?php echo ($_SESSION['r1'] == "p") ? 'checked="checked"' :''; ?><?php echo ($_POST['r1'] == 'p') ? 'checked="checked"' : ''; ?> />Off</li>
</ul>
</form>



<?php
session_start();

//I don't know what to write here in order to make it work :S ?>

also when i open the page both buttons are unselected how could i do that the button 'A' remain checked by default when none selected

You need to translate your _POST variables into _SESSION variables. It works at first because you allow either POST or SESSION variables to set the check:

<?php echo ($_SESSION['r1'] == "o") ? 'checked="checked"' : ''; ?><?php echo ($_POST['r1'] == 'o' ) ? 'checked="checked"' : ''; ?>

But this is unnecessary. At the very top of your page you should have this:

<?php
session_start();
if (isset($_POST['r1'])){
    $_SESSION['r1']=$_POST['r1'];
}
?>

and then down below you only need

<?php echo ($_SESSION['r1'] == "o") ? 'checked="checked"' : ''; ?>

Extra note: Make sure that the session_start() call occurs at the very beginning of the page, and that it occurs at the very top of every page where you want the session variable to be available.

session_start();
$_SESSION['r1'] = $_REQUEST['r1'];

When you submit a selection to your php script, you need to get/post/request the variable and store it into a session variable after starting the session. Then in each php file you can add a session_start() statement, and you will be able to use all of the session variables in that script. You can also set the session cookie so that it expires when the user closes their browser session_set_cookie_params(0);, or when hitting a log out button by using session_destroy();. Once you have the session variable stored, you can use it on all your pages to set the 'checked' attribute of the radio button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM