使用 php 保存表单值并使用 SESSION 调用 cookie


Saving form values with php and calling cookie using SESSION

我正在用html制作表单。当一个人点击提交时,它会检查某些字段是否正确填写,到目前为止,形式非常简单。

但是,如果有人刷新页面,我想保存输入到字段中的文本。因此,如果刷新页面,文本仍在字段中。

我正在尝试使用 php 和 cookie 来实现这一点。

   // Cookie
   $saved_info = array();
   $saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][', 
   $_COOKIE['offer_saved_info']) : array();
   foreach($saved_infos as $info)
   {
      $info_ = trim($info, '[]');
      $parts = explode('|', $info_);
      $saved_info[$parts[0]] = $parts[1];
   } 
   if(isset($_SESSION['webhipster_ask']['headline']))
      $saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
    // End Cookie

现在对于表单输入字段:

<div id="headlineinput"><input type="text" id="headline" 
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ? 
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>" 
tabindex="1" size="20" name="headline" /></div>

我是 PHP 中使用 SESSION 的新手,所以我的问题是:

有没有更简单的方法可以在不使用上述 cookie 的情况下实现这一目标?或者我在上面提到的代码中做错了什么?

第一件事是我很确定你的回声应该在它周围有圆括号,例如:

echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)

虽然我认为这不是你问的唯一问题。

如果您通过表单提交数据,为什么不使用表单值进行验证,并在 html 输入值中使用表单值。只有在验证数据并继续后,我才会将它们存储到我的会话中。

例如:

<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
    //validate all $_POST values
    if(!empty($_POST['headline']))
    {
        $errors[]="Your headline is empty";
    }   
    if(!empty($_POST['something_else']))
    {
        $errors[]="Your other field is empty";
    }   
    if(empty($errors))
    {
        //everything is validated   
        $_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
        header("Location: wherever.php");
    }
}
if(!empty($errors))
{
    foreach($errors as $val)
    {
        echo "<div style='color: red;'>".$val."</div>";
    }   
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>