0

简介:我正在尝试在 $_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>
4

1 回答 1

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'];,您将开始获得结果。

于 2013-10-11T16:27:35.147 回答