-1

i have a setcookie function in php. i have a jquery dialog with an input field an a submit button. when i type in a postcode in the input field and push submit the postcode is saved in an php cookie.

This cookie wil be shown in an input field on the mainpage.

Now is my problem that when i did not have a cookie set, so for example i leave the input field blank and click submit it gives me an error. but in the input field.

I am using codeigniter so that could be the problem.

Error:

Message: Undefined index: name Filename: views/navmenu.php Line Number: 33

My set cookie and form code:

<div id="dialog" class="hidden" title="Welkom bij OostWestRegioBest.nl">
Vul hier uw postcode in.
<form method="post" action"">
Postcode: <input type="text" name="name" size="25">
<input type="submit" value="Opslaan">
<input type="hidden" name="submitted" value="true">
</form>

<?php
// set the cookie with the submitted user data
setcookie('name', $_POST['name']);
?>

<?php
    if(isset($_POST['Submit']))
    {
    header("location: {$_SERVER['PHP_SELF']}");
    }
?>

</div>

My input field where the cookie will be shown at.

<input type="text" value='<?php echo $_COOKIE['name'] ?>'>  

Hope someone could help me.

thanks.

Till Helge
  • 9,253
  • 2
  • 40
  • 56
Kees Sonnema
  • 5,759
  • 6
  • 51
  • 106

2 Answers2

1

Set cookie only if $_POST contains an element with index - name.

You can try this.

<?php
    // set the cookie with the submitted user data
    setcookie('name', isset($_POST['name']) ? $_POST['name'] : "");
?>

Or set cookie only if it contains an element with index - name.

<?php
    if (isset($_POST['name'])) {
       // set the cookie with the submitted user data
       setcookie('name', $_POST['name']);
    }
?>

Choose any one based on your requirement.

Sasidhar Vanga
  • 3,384
  • 2
  • 26
  • 47
1

Please set the cookie only after the form is submitted

if(isset($_POST['Submit'])){
     setcookie('name', $_POST['name']);
}

You can change the input field as

<input type="text" value='<?php echo isset($_COOKIE['name']) ? $_COOKIE['name'] : '' ?>'>
Rohit Subedi
  • 560
  • 3
  • 13