Solved

Simple Cookie

Posted on 2004-10-03
17
230 Views
Last Modified: 2008-03-06
Hi,

How do I create a simple cookie that would contain for example: FullName, Email, Username, Password, Domain, Plan, CheckID ?

The CheckID would be a MD5 codeword that I will hardcode in and will be used later to see if the cookie is authentic.

So, how do I create and write this ? and then later read it back ? also how do I destroy it ?

Thanx
0
Comment
Question by:MirageSF
  • 6
  • 2
  • 2
  • +3
17 Comments
 
LVL 36

Assisted Solution

by:Zyloch
Zyloch earned 62 total points
ID: 12214190
Hi MirageSF,

To set, use setcookie
http://us2.php.net/setcookie

To get, use
$_COOKIE['cookiename'];

Regards,
Zyloch
0
 
LVL 4

Expert Comment

by:Skonen
ID: 12214716
You could use individual cookies like:

setcookie("Fullname", "whoever",  time() + 3600);  // Expire in one hour

And retrieve it with $_COOKIE:

$myvar = $_COOKIE['Fullname'];


Or you can pack the values into one cookie using explode (http://us2.php.net/explode) and implode (http://us2.php.net/implode). Which means less cookies and expire times to keep track of.
0
 
LVL 2

Expert Comment

by:Rajkumar_G
ID: 12215086
Here is a simple example for Cookies creation, retrieveing data from cookies and deleting cookies.
I think this will be useful for u,U an customise it according to your requirements.

cookie_ex.html
--------------
<html>
<head>
</head>
<body>
<form name="cookie_example" method="post" action="cookie_ex.php">
  Fullname  :<input type="text" name="fullname"><br>
  Email     :<input type="text" name="email"><br>
  Username  :<input type="text" name="username"><br>
  Password  :<input type="text" name="password"><br>
  Domain    :<input type="text" name="domain"><br>
  Plan      :<input type="text" name="plan"><br>
  checkid   :<input type="text" name="checkid"><br>
  <input type="submit" name="Submit">
</form>
</body>
</html>



cookie_ex.php
-------------
<?
      setcookie ("cookie[full]", $_POST['fullname'], time()+604800);
      setcookie ("cookie[email]", $_POST['email'], time()+604800);
      setcookie ("cookie[user]", $_POST['username'], time()+604800);
      setcookie ("cookie[pass]", $_POST['password'], time()+604800);
      setcookie ("cookie[domain]", $_POST['domain'], time()+604800);
      setcookie ("cookie[plan]", $_POST['plan'], time()+604800);
      setcookie ("cookie[checkid]", $_POST['checkid'], time()+604800);

      if(setcookie("cookie","", time()+604800))
         {
           echo "<br>Cookie Deleted<br>";
         }
      else
         {
           echo "<br>Cookie Exists<br>";
         }


      if (isset($_COOKIE['cookie']))
       {
         foreach ($_COOKIE['cookie'] as $name => $value)
           {
             echo "$name : $value <br />\n";
           }
       }

?>


Run this code, so that u can understand it well. Then it will be easy for u to customise it.
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12215440
Using one cookie for all of the information....

(sensible if you are accessing all of the stored information on the same page, if you need to access different data on different pages then it may make sense to break them up into seperate cookies.

For the sake of example i am going to assume you have the values stored in local variables. and you have MD5'd the CheckID (using for example $CheckID = md5($CheckID);

Setting the cookie:

<?php
setcookie("mycookie","$FullName|$Email|$Username|$Password|$Domain|$Plan|$CheckID",time()+31556926);
?>

3 of the setcookie parameters have been used above, the name of your cookie, the data to store in it and a time stamp (here this is the current time plus one year - so it is valid until a year from now).

Reading the cookie:

<?php
$mycookie = $_COOKIE['mycookie'];
$elements = explode("|",$mycookie); Returns an array of the values stored in the cookie
echo $elements[0]; //FullName
echo $elements[1]; //Email
echo $elements[2]; //Username
echo $elements[3]; //Password
echo $elements[4]; //Domain
echo $elements[5]; //Plan
echo $elements[6]; //CheckID
?>

For observation purposes you can view the array contents just using:

<pre>
<?php
$mycookie = $_COOKIE['mycookie'];
$elements = explode("|",$mycookie); Returns an array of the values stored in the cookie
print_r($elements);
?>
</pre>

Deleting the cookie:

<?php
setcookie("mycookie","",time() - 3600); //sets the cookie with an expiry time in the past
?>

You may handle deleting the cookie like this (supposing it was handled on index.php) have a link with a query string...

<a href="index.php?delete">Link</a>

Then in your php:

<?php
if (isset($_GET['delete'])) setcookie("mycookie","",time() - 3600);
?>

Best Wishes

|)iablo
0
 

Author Comment

by:MirageSF
ID: 12217906
Array ( [0] => [1] => [2] => [3] => [4] => )
Warning: Cannot modify header information - headers already sent by (output started at /home/storm/domains/storm.com/public_html/complete.php:4) in /home/storm/domains/storm.com/public_html/complete.php on line 11


When I go to collect the cookie information after a third party website has been loaded, I get an empty cookie, and the warning messsage ?

Line 11 is setcookie("mycookie","",time()-3600);

0
 
LVL 27

Accepted Solution

by:
Diablo84 earned 63 total points
ID: 12217950
you must use setcookie BEFORE any output (php echo/print, html, new lines outside of <?php tags) otherwise it cant send the cookie data in the http header and you will see that error.
0
 
LVL 5

Expert Comment

by:prsupriya
ID: 12219867
Hi!

How about this?

<?
$arraynew=array("FullName"=>setckval("FullName", "FullNameval"),"Email" =>setckval("Email", "Emailval"),
"Username" =>setckval("Username", "Usernameval"),"Password" =>setckval("Password", "Passwordval"),
"Domain" =>setckval("Domain", "Domainval"),"Plan" =>setckval("Plan", "Planval"),
"CheckID" =>setckval("CheckID", "CheckIDval"));
?>
<?
function setckval($ckname,$ckval){
      setcookie($ckname, $ckval);
      return $_COOKIE["$ckname"];
      }
print_r(array_values($arraynew));
?>

Good Luck,
S:
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 4

Expert Comment

by:Skonen
ID: 12222402
Mirage, you can use an output buffer to get rid of that warning. Use

ob_start();

Right after your first <?php tag or before any output, then after you set your cookie, put the following line:

ob_end_flush();

So in your case it's probably safe to use ob_end_flush() following line 11.
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12222495
Really just better to just correct the code flow in the script.

Its only line 11 so it is most likely a new line outside of the <?php tag, a 2 second reshuffle of the code flow will fix this rather then turning to output buffering.
0
 

Author Comment

by:MirageSF
ID: 12223986
// Code below creates the cookie and then loads another site.

<?php
session_start();
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$domain = $_POST['domain'];
$username = $_POST['username'];
$password = $_POST['password'];
echo $fullname;
setcookie("mycookie","$fullname|$email|$username|$password|$domain",time()+31556926);
Header("Location: https://www2.2checkout.com/2co/buyer/purchase?sid=540281&quantity=1&product_id=$pid&demo=Y");
?>

// Code below is loaded after the 2checkout.com site loads it., but fails at line 11 with the error as above.

<?php
$mycookie = $_COOKIE['mycookie'];
$elements = explode("|",$mycookie);
print_r($elements);

echo $elements[0]; //FullName
echo $elements[1]; //Email
echo $elements[2]; //Username
echo $elements[3]; //Password
echo $elements[4]; //Domain
setcookie("mycookie","",time() - 3600);
?>

// btw the array seems to be empty anyway for some reason !  The variables being past are correct.

0
 
LVL 36

Expert Comment

by:Zyloch
ID: 12224083
In the first case, have this:

<?php
session_start();
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$domain = $_POST['domain'];
$username = $_POST['username'];
$password = $_POST['password'];
setcookie("mycookie","$fullname|$email|$username|$password|$domain",time()+31556926);
Header("Location: https://www2.2checkout.com/2co/buyer/purchase?sid=540281&quantity=1&product_id=$pid&demo=Y");
?>

The echo is pointless because you're redirecting anyways.


For the second, move your setcookie function to between your

$element = explode line and your print_r line.
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12224831
yes quite, you don't need echo $fullname;

As i said above anything in the form of new lines echo/print or html tags will case the same problem as both header and setcookie require data to be sent via the http headers.

In the case of the second example you need to control the code flow

<?php
$mycookie = $_COOKIE['mycookie'];
$elements = explode("|",$mycookie);
print_r($elements);

echo $elements[0]; //FullName
echo $elements[1]; //Email
echo $elements[2]; //Username
echo $elements[3]; //Password
echo $elements[4]; //Domain
?>

You cannot put it prior to the above code as it will delete the cookie before reading the information, at the same time you can put it after because you have not yet read the information from it, so, if you do need to delete it at this point then you can do as Zyloch pointed out which is to read the information from it, delete it then output the information you read. The alternative is putting it in a conditional statement to control its execution, it depends when and why you delete it when you do.

The bottom line is anything that sends data via the headers (header,setcookie etc) cannot go after you have outputted data unless you have turned output buffering on (not needed in this case) so make sure your code flow is correct with this in mind.
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12518144
I am fine with a split but i would like to propose a majority split - to Diablo84 -  as it is my solution that is being used. A partial split to Zyloch for the support pointing out the issue with MirageSF's implementation of the code.
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12522643
A 1 point majority was not quite what i had in mind :)
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
spacing 5 30
lastpass auto fill login form 5 24
Editing login page in zencart. 2 14
Help cleaning out CSS 2 29
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now