在POST后设置cookie会导致“未定义索引”;通知


Setting cookie after POST gives "undefined index" notice

我有一个setcookie函数在php。我有一个jquery对话框与输入字段和提交按钮。当我在输入字段中输入邮政编码并推送提交时,邮政编码被保存在PHP cookie中。

此cookie将显示在主页面的输入字段中。

现在是我的问题,当我没有一个cookie集,所以,例如,我离开输入字段空白,点击提交它给我一个错误。但是在输入字段

我正在使用codeigniter,所以这可能是问题。

错误:

Message: Undefined index: name Filename: views/navmenu.php Line数量: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>

cookie将显示在的输入字段。

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

希望有人能帮助我。

谢谢。

请在表单提交后再设置cookie

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

您可以将输入字段更改为

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

仅当$_POST包含index - name的元素时设置cookie

你可以试试这个

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

或者只在包含index - name的元素时设置cookie。

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