对于用户可以在表单中输入的值,我该如何设置 cookie 值和名称?我该如何在第二页上显示该值? (我不能不使用 cookie,所以虽然可能有更聪明的方法来做到这一点,但我只是想知道如何使用 cookie 来做到这一点!!)谢谢!
<?php
setcookie($color, 'color');
setcookie($name, 'name');
?>
<?php
echo "<form action=\"form_data.php\" method=\"post\">";
echo "favorite color:<input type=\"text\" name=\"color\" size=\"20\"><br/>";
echo "name:<input type=\"text\" name=\"name\" size=\"20\"><br/>";
echo "<input type=\"submit\" value=\"Submit\" />";
echo "<br /><input type=\"hidden\" name=\"submitted\" value=\"true\" />";
?>
form_data 上的数据:
<?php
echo "<b>fav color:</b>".$_COOKIE['color'];
echo "<b>name:</b>".$_COOKIE['name'];
?>
首先,你有你的表格:
<?php
echo "<form action=\"form_data.php\" method=\"post\">";
echo "favorite color:<input type=\"text\" name=\"color\" size=\"20\"><br/>";
echo "name:<input type=\"text\" name=\"name\" size=\"20\"><br/>";
echo "<input type=\"submit\" value=\"Submit\" />";
echo "<br /><input type=\"hidden\" name=\"submitted\" value=\"true\" />";
?>
然后在form_data.php中:
<?php
// set the cookie with the submitted user data
setcookie('color',$_POST['color']);
setcookie('name', $_POST['name']);
echo "<b>fav color:</b>".$_COOKIE['color'];
echo "<b>name:</b>".$_COOKIE['name'];
?>
但是,您会注意到 $_COOKIE 变量尚不可用...如果您重新加载该页面,它们就会出现。
为了适应 cookie 的这种行为,您可以在 data.php 表单中设置重定向:
<?php
if (!empty($_POST)) {
// set the cookie with the submitted user data
setcookie('color',$_POST['color']);
setcookie('name', $_POST['name']);
// redirect the user to final landing page so cookie info is available
header("Location:form_data.php");
} else {
echo "<b>fav color:</b>".$_COOKIE['color'];
echo "<b>name:</b>".$_COOKIE['name'];
}
?>
您可以将它们重定向到任何合适的地方。希望这有帮助,祝你好运!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)