Jump to content

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'; }

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.