使用php保存表单值并使用会话调用cookie
我正在用html制作一个表单。当一个人点击submit时,它会检查某些字段是否正确填写,这是迄今为止非常简单的表单 但是,如果有人刷新页面,我想保存输入到字段中的文本。因此,如果刷新页面,文本仍在字段中 我正在尝试使用php和cookie来实现这一点使用php保存表单值并使用会话调用cookie,php,forms,session,cookies,session-cookies,Php,Forms,Session,Cookies,Session Cookies,我正在用html制作一个表单。当一个人点击submit时,它会检查某些字段是否正确填写,这是迄今为止非常简单的表单 但是,如果有人刷新页面,我想保存输入到字段中的文本。因此,如果刷新页面,文本仍在字段中 我正在尝试使用php和cookie来实现这一点 // Cookie $saved_info = array(); $saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][', $_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>
首先,我非常确定echo的周围应该有圆括号,如:
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>
在$\u会话中保存所有内容。从这里您可以访问所有内容。或者您尝试jquery cookie插件,将所有内容保存在cookie中,并通过JSF从cookie读取数据,而将这些内容保存在cookie中的最佳方式是通过json字符串(数组到json)@brandelizer如果您在会话中保存,则不需要使用json。您可以将数组直接放入$\u会话
,PHP负责将其正确序列化。是的,您是对的。但我的意思是保存cookie(编辑它)看这里