Retrieve $_SESSION value in Input value

2019-08-30 11:26发布

问题:

I am working with a basic registration form , if the user presses submit button , i want to store the input values to a session and also to retain the same user data into the inputfield . With the following code i can able to temporarily store and retrieve but only when i press submit button twice. my basic requirements are - I want to retain the user data after pressing "submit". - I Want to retain the radio , checkbox values also. - It is possible to retain the input values even though we Refresh the page.

the code follows , please give some suggestion regarding my problem

<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
<style type="text/css">
ul li
{ 
 list-style:none; 
}   
form
{
border:1px solid #ccc;
width:500px;
margin:0 auto;
}
</style>
</head>
<body>
<?php session_start(); ?>
<form action="<?php $_PHP_SELF ?>" method="post" name="register" >
<h4>User Registration</h4>
<ul>
  <li><label>User Name</label></li>
  <li>
  <input type="text" name="user" size="20" value="
  <?php echo isset($_SESSION['user']) ? $_SESSION['user'] : ''; ?>"></li>
  <li><label>Email</label></li>
  <li><input type="text" name="email" size="25" value="
  <?php echo isset($_SESSION['email']) ? $_SESSION['email'] : ''; ?>"></li>
  <li>Gender</li>
  <li><input type="radio" name="gender">Male</li>
  <li><input type="radio" name="gender">Female</li>
  <li>Computer Knowledge</li>
  <li><input type="checkbox" name="c">C Language</li>
  <li><input type="checkbox" name="cplus">C++ Language</li>
  <li><input type="checkbox" name="java">Java</li>
  <li><input type="checkbox" name="php">PHP</li>
  <li><input type="checkbox" name="python">python</li>
  <li><input type="submit" name="submit" value="submit">
 </ul>
 </form>
 <?php 
   if (isset($_POST['submit']))  
    {
    $_SESSION['user'] = $_POST['user'];
    $_SESSION['email'] = $_POST['email'];
    }
 ?>
 </body>
 </html>

Thanks in advance

回答1:

this <?php session_start(); ?> should come right on top of the page before everything else! it should start like this;

 <?php session_start(); ?>
 <!DOCTYPE html>

you should be getting a php error right now saying "Fatal error; headers already sent" or something like that.

the $_SESSION variable will not be available to you if the server did not get the instruction session_start(); in the very first line of your code



回答2:

Move this part at the top of your script, just after session_start(); :

 <?php 
   if (isset($_POST['submit']))  
    {
    $_SESSION['user'] = $_POST['user'];
    $_SESSION['email'] = $_POST['email'];
    }
 ?>

Also, as @pythonian29033 said, session_start(); should be written before you output any content.