[英]PHP : Notice: Undefined index: NameFilledIn in C:\xampp\htdocs\vdab\cookies.php on line 9
I'm new at PHP and although i found similar solutions for this error, i cannot solve it yet. 我是PHP的新手,尽管我针对此错误找到了类似的解决方案,但仍无法解决。 When running this page i get the error: Notice: Undefined index: NameFilledIn in C:\\xampp\\htdocs\\vdab\\cookies.php on line 9. When I fill in a name and refresh the page, it does work. 运行此页面时,出现错误:注意:未定义索引:第9行的C:\\ xampp \\ htdocs \\ vdab \\ cookies.php中的NameFilledIn。当我填写名称并刷新页面时,它确实起作用。 Once the time of the cookie is passed and I refresh the page, I get the same error as in the beginning. 一旦Cookie的时间过去了,并且刷新了页面,就会收到与开始时相同的错误。
The complete code is: 完整的代码是:
<?php
if (!empty($_POST["txtName"]))
{
setcookie("NameFilledIn", $_POST["txtName"],time() + 60);
$name = $_POST["txtName"];
}
else
{
$name = $_COOKIE["NameFilledIn"];
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<?php
if (isset($name))
{
print ("Welcom, ") . $name;
}
?>
<form action="cookies.php" method="POST">
Uour name: <input type="text" name="txtName" value="<?php print ($name);?>">
<input type="submit" value="Send">
</form>
<br><br>
<a href="cookies.php">Refresh the page</a>
</body>
</html>
The notice Undefined index:
occurred because you are trying to access cookie without checking whether it is set or not. 出现Undefined index:
通知,是因为您尝试访问cookie而不检查是否设置了cookie。 Use isset()
to check if they are declared before referencing them like, 使用isset()
在引用它们之前检查它们是否已声明,
if (!empty($_POST["txtName"]))
{
setcookie("NameFilledIn", $_POST["txtName"],time() + 60);
$name = $_POST["txtName"];
}
else
{
if(isset($_COOKIE["NameFilledIn"])) // only if it is set
$name = $_COOKIE["NameFilledIn"];
}
The same thing you have to check everywhere you are trying to echo/access the PHP variables. 您必须在试图回显/访问PHP变量的所有地方检查同一件事。
<input type="text" name="txtName" value="<?php if(isset($name)) { print ($name); } ?>">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.