Jump to content

[SOLVED] Bit of a cookie problem


LiamProductions

Recommended Posts

Hey.

 

I'm just doing something simple trying to store the input from one page into a cookie so it can be outputted on other pages heres the scripts:

 

<form method="post" action="secondpage.php">
Name: <input type="text" name="name">
<input type="submit" value="go">
</form>

 

and...

 

<?php
setcookie("user", "$name", time()+3600);
extract($_COOKIE); 
if (isset($_COOKIE['user']))
   echo "Welcome " . $_COOKIE['user'] . "Enjoy the site<br />";
else
   echo "Hello Guest!!<br />"
?>

 

Its just comming out as "Hello Guest!!"

when the form is submitted i want it to come out as Welcome [NAME THEY INPUTTED] Enjoy the site

but if they didnt input a name i want it to output Hello Guest!!

 

any suggestions on what im doing wrong

?

Link to comment
https://forums.phpfreaks.com/topic/64522-solved-bit-of-a-cookie-problem/
Share on other sites

Try using the $_POST superglobal.  $name wasn't defined in that snippet.  You also don't need extract().

 

<?php
$name = $_POST['name'];
setcookie("user", "$name", time()+3600);
if (isset($_COOKIE['user']))
   echo "Welcome " . $_COOKIE['user'] . "Enjoy the site<br />";
else
   echo "Hello Guest!!<br />"
?>

Theoretically there is nothing wrong with you're script.

But two things, you are not checking if the user has actually submitted the form, and the "$name" could give an other message.

 

Try this script,

 

First script.

<html>
<head>
</head>
<body>
<form method="post" action="secondpage.php">
Name: <input type="text" name="name">
<input type="submit" value="go">
</form>
</body>
</html>

 

Second script.

<?php
if(isset($_POST['submit'])){
$clean_name = htmlspecialchars($_POST['name']);
if (empty($clean_name)){
echo 'You did not enter a name, please go back and do so.'; 
} else {
$set_cookie = setcookie('Name', $clean_name, time()+3600);
if (!$set_cookie){
echo 'Please enable cookies in you're browser.';
} }
if (isset($_COOKIE['Name')){
echo 'Hello there ' . $_COOKIE['Name'];
} else {
echo 'Welcome Guest'; }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.