Keep form values after submit PHP with cookies

2019-08-04 17:34发布

问题:

I am looking for a way to keep form values after submit with cookies (after going to page2 and going back to page_form). I am really trying but i need you help guys.

I tried this but it didn't work

<? 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>

回答1:

I prefer using SESSION variables before cookies. Here is an example code:

On the form recieving page:

session_start();
$_SESSION['from'] = $_POST['from'];
$_SESSION['area_html'] = $_POST['area_html'];

Then on your other page:

<?php session_start(); ?>
<!-- here is your html header etc -->
From: <?php echo $_SESSION['from']; ?><br>
Area HTML: <?php echo $_SESSION['area_html']; ?>

Note that the session_start(); part must be stated BEFORE any other HTML output.

HTML syntax for form should read:

<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>

Note the type of the INPUT tag and the change how values should be inserted into a TEXTAREA.



回答2:

You can save form values in the php session using $_SESSION variable and not the cookies.

here are several tutorials which help you to do this.

session_php 1 session_php 2



回答3:

Just copy and paste this code in test.php and run & refresh it.. you will understant how it worked.

<?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>