Reputation: 73
I have a problem with my php script. I would like to print the value of my cookie, as "value" in the form I have created. But it does not print it and my website does not look like I want. Here is my code. And the error I got is: Notice: Undefined index: pseudo in C:\xampp\htdocs\OpenClassroom\index.php on line 4
Thanks in advance.
<?php
if (isset($_COOKIE['username']))
{
setcookie('username', htmlspecialchars($_POST['pseudo']), time() + 31536000, null, null, false, true);
}
else
{
setcookie('username', 'NewUsername', time() + 365*24*3600, null, null, false, true);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Mini-chat</title>
</head>
<style>
form
{
text-align:center;
}
</style>
<body>
<!--Form-->
<form action="commentaires.php" method="post">
<p>
<label for="pseudo">Pseudo</label> : <input type="text" value="<?php echo $_COOKIE['username'] ; ?>" name="pseudo" id="pseudo" /><br />
<label for="message">Message</label> : <input type="text" name="message" id="message" /><br />
<input type="submit" value="Envoyer" />
</p>
</form>
Upvotes: 1
Views: 159
Reputation: 22911
$_COOKIE
doesn't set the cookie when using setcookie()
on the first request according to the documentation:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
So...subsequent requests will show properly. A quick and dirty solution is to set it manually the first time:
<?php
if (isset($_COOKIE['username']))
{
setcookie('username', htmlspecialchars($_POST['pseudo']), time() + 31536000, null, null, false, true);
}
else
{
setcookie('username', 'NewUsername', time() + 365*24*3600, null, null, false, true);
$_COOKIE['username'] = 'NewUsername';
}
?>
Upvotes: 2