[英]Keep form values after submit PHP with cookies
我正在尋找一種方法來提交帶有cookie的表單(進入page2並返回page_form之后)后保持表單值。 我確實在嘗試,但是我需要您的幫助。
我嘗試了這個,但是沒有用
<? php
if (isset($_POST['Infos_test']))
{
$expire = 8*3600;
setcookie("Infos_test", $_POST['from']&|&$_POST['area_html'], time()+$expire);
}
?>
.....
<?php
if (isset($_COOKIE['Infos_test']))
{
$Infos_test = explode("&|&", $_COOKIE['Infos_test']);
}
?>
.....
<input type="text" name="from" style="width:350px" value="<?php echo $Info_test[0]; ?>"/>
<textarea valign="top" name="area_html" style="width:350px; height:150px; resize:none;" /><?php echo $Info_test[1]; ?></textarea>
我更喜歡在Cookie之前使用SESSION變量。 這是示例代碼:
在表單接收頁面上:
session_start();
$_SESSION['from'] = $_POST['from'];
$_SESSION['area_html'] = $_POST['area_html'];
然后在另一頁上:
<?php session_start(); ?>
<!-- here is your html header etc -->
From: <?php echo $_SESSION['from']; ?><br>
Area HTML: <?php echo $_SESSION['area_html']; ?>
注意session_start();
必須在任何其他HTML輸出之前聲明部分。
表單的HTML語法應為:
<input type="text" name="from" style="width:350px" value="<?php echo $_SESSION['from']; ?>" />
<textarea valign="top" name="area_html"><?php echo $_SESSION['area_html']; ?></textarea>
請注意INPUT標記的類型以及應將值插入TEXTAREA的方式的更改。
只需將這段代碼復制並粘貼到test.php
然后運行並刷新它即可..您將了解它的工作原理。
<?php
if (isset($_POST['sub'])) {
echo "Values from POST <br />";
echo "<pre>";
print_r($_POST);
echo "</pre>";
$post_arr = $_POST;
echo "<pre>";
print_r($post_arr);
echo "</pre>";
echo "<pre>";
print_r(serialize($post_arr));
echo "</pre>";
$expire = 8*3600;
setcookie("Cookie_Info", serialize($post_arr), time()+$expire);
}
if (isset($_COOKIE['Cookie_Info'])) {
$data = unserialize($_COOKIE['Cookie_Info']);
} else {
$data = array(
'from' => '',
'area_html' => ''
);
/* in above array add what ever fields in a form with same field name */
}
echo "This is what we get from cookie";
echo "<pre>";
print_r($data);
echo "</pre>";
?>
To view Cookie, it need browser refres one time <br />
<form name="test_form" method="post">
<input type="text" name="from" value="<?php echo $data['from']; ?>" /> <br />
<textarea rows="3" name="area_html" ><?php echo $data['area_html']; ?></textarea> <br />
<input type="submit" name="sub" value="Submit" />
</form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.