Mohammed Shuheb
Mohammed Shuheb

Reputation: 47

How to store html form data in a cookie so it's still there after the form is submitted

I have made this html form, it submits all the information to a MySQL database. Pretty simple stuff.

How do I store the username in a cookie so that once it's entered? I would like to ensure that once the user enters their username once, it pre-populates the username field in the future.

<!-- Message board submissionform -->

<form id="frmMB" name="frmMB" action="insert.php" method="post" enctype="multipart/form-data">

<label class="name"><input name="name" placeholder="Enter your name" type="text" id="name" onFocus="if(this.value=='Enter your name'){this.value=''};" onBlur="if   (this.value==''){this.value='Enter your name'};" value="Enter your name" size="80" maxlength="10" ></label>
<br />
<label class="message">
  <input name="post" placeholder="Enter a message" type="text" id="post" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;" value="Enter a message" size="80" maxlength="140" data-maxsize="3">
</label>
<br />
<label>
<input name="Submit" class="large button" type="submit" value="submit">
</label>

Upvotes: 2

Views: 2511

Answers (2)

vlex
vlex

Reputation: 128

First you need to start a session -> session_start()

Once done so, you have created a public $_SESSION array and can add elements to it. Easiest way to do so is:

<?php

if(isset($_POST['username'])){
    sesion_start();

    $_SESSION['username'] = $_POST['username'];

}
...

Cheers!

Upvotes: 1

John In&#39;t Hout
John In&#39;t Hout

Reputation: 304

I think something like this would just do this trick.

setcookie($_POST['name'], $value, time()+3600);

if(isset($_COOKIE['name']) && !empty($_COOKIE['name']))
{
    // do some stuff here because the name is set in the cookie.
}

Upvotes: 2

Related Questions