使用会话在PHP表单上记住用户

时间:2013-10-11 04:38:15

标签: php forms session

简介:我正在尝试在$ _SESSION上学习PHP。我试图做的是调用通过会话分配的值,当您关闭选项卡时,将保留指定的值,并在浏览器中打开选项卡时在浏览器上回显它。

问题:我的代码出了问题,由于某些原因我无法回应表单中输入的值。

表格如下:

Name:_____________
Email:_____________ Remember me? __  SUBMIT

只有当用户点击“记住我”时,我才这样做$ _SESSION ['name'] =“John”和$ _SESSION ['email'] =“someemail@email.com”。

如果您关闭浏览器上的“标签”但浏览器本身不应该回显......

John
someemail@email.com

Here's your download link (some link here)...

但是当然如果你关闭浏览器,会话就会丢失。可以使用Cookie,但我正在开展会议以了解更多信息。

下面的代码运行但由于某种原因我无法回显$ _SESSION变量的值。

<?php 

 //Start session
    session_start(); 
    // session
    if (isset($_POST['remember'])) {

$customer_name = $_SESSION['name'];
if (!($customer_name)) {
$customer_name = $_POST['name'];
}
$customer_email = $_SESSION['email'];
if (!($customer_email)) {
$customer_email = $_POST['email'];
}

    }


//If form submit validate
    if (isset($_POST['Submit'])) {
    // Santize fields here but FILTER_VALIDATE_STRING isn't necessary as there is no absolute way 
    //to validate names absolutely 
    // Also shows error message if there's error 
    if ($_POST['name'] != "") {
        $_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
        if ($_POST['name'] == "") {
            $errors .= 'Please enter a valid first name.<br/><br/>';
        }
    } else {
        $errors .= 'Please enter your first name.<br/>';
    }

    // Sanitize and validate email
    // Error message shows if any
    if ($_POST['email'] != "") {
        $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors .= "$email is NOT a valid email address.<br/><br/>";
        }
    } else {
        $errors .= 'Please enter your email address.<br/>';
    }


    // If no errors, submitted form is emailed
    if (!$errors) {

        echo "I did something!<br /><br />"; // might add some message
        //downloadLink();
        echo "<br /><br />";



    }




    } else {
        echo '<div id="error">' . $errors . '<br /></div>';
    }



?>

<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name:
<?php
  if (isset($_SESSION['name'])) {
    echo $_SESSION['name']."<br />";
  }
else {
?> 
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="25" /><br />
<?php } ?>

Email:
<?php
  if (isset($_SESSION['email'])) {
    echo $_SESSION['email']."<br /><br />";

    // echo link.. downloadLink();
  }
else {
?>  
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="25"/> 
<input type="checkbox" name="remember" /> Remember me
<input type="submit" name="Submit" />
<?php } ?>


</form>
</div>

1 个答案:

答案 0 :(得分:1)

将其放在session_start();

下的开头
if (!isset($_SESSION['name'])) { 
echo "Your session is not good"; 
} else { echo "Session is set"; 
}

然后将$customer_name = $_SESSION['name'];替换为$_SESSION['name']=$_POST['remember'];,您将开始获得结果。