Php 在POST后设置cookie将给出;未定义索引“;通知

Php 在POST后设置cookie将给出;未定义索引“;通知,php,jquery,codeigniter,cookies,setcookie,Php,Jquery,Codeigniter,Cookies,Setcookie,我在php中有一个setcookie函数。 我有一个带有输入字段和提交按钮的jquery对话框。当我在输入字段中键入邮政编码并按下提交按钮时,邮政编码保存在php cookie中 此cookie将显示在主页上的输入字段中 现在的问题是,当我没有设置cookie时,例如,我将输入字段留空,然后单击submit,它会给我一个错误。但是在输入字段中 我正在使用codeigniter,所以这可能是问题所在 错误: 消息:未定义索引:名称文件名:views/navmenu.php行 电话:33 我的设置c

我在php中有一个setcookie函数。 我有一个带有输入字段和提交按钮的jquery对话框。当我在输入字段中键入邮政编码并按下提交按钮时,邮政编码保存在php cookie中

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

现在的问题是,当我没有设置cookie时,例如,我将输入字段留空,然后单击submit,它会给我一个错误。但是在输入字段中

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

错误:

消息:未定义索引:名称文件名:views/navmenu.php行 电话:33

我的设置cookie和表单代码:

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

Vul hier uw的邮政编码为。
邮政编码:

仅当$\u POST包含索引名为的元素时才设置cookie

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

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

或者仅当cookie包含具有索引名的元素时才设置cookie

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


根据您的要求选择任意一个。请仅在提交表单后设置cookie

if(isset($_POST['Submit'])){
     setcookie('name', $_POST['name']);
}
您可以根据需要更改输入字段

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

即使没有发送表单,您也可以访问
$\u POST['name']
。将
setcookie()
行放入下面的
if
块中,您应该会没事。我们不需要查看
views/navmenu.php
来回答这个问题吗?OP中的最后一行来自my navmenu.php,但我用Rohit Subedi的回答解决了它。错误仍然显示出来。它与codeigniter相关,所以我可以以某种方式隐藏此错误吗?因为这只是没有设置cookie时的问题。请尝试第一个。它将在cookie中设置空值,并在输入中使用相同的值。是的,但这就是问题所在。当它为空时,它会给我错误。当它不为空时就可以了。根据给定的错误,哪条语句在第33行?这条:这不对。因为if(isset($\u POST['Submit']){必须是if(isset($\u POST['name']){您的第二个代码确实有效!感谢Vanga Sasidhar,他向我指出了这一点。