12 Replies - 29799 Views - Last Post: 26 May 2011 - 10:54 AM Rate Topic: -----

#1 itdoell   User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 239
  • Joined: 13-January 11

Setting multiple values to a single cookie?

Posted 25 May 2011 - 02:16 PM

Is it possible to set a single cookie that can call multiple values?

For example if I wanted to get the client's first and last name could I do $_COOKIE['mycookie']['first_name'] and then $_COOKIE['mycookie']['last_name'] ?

If this is possible, how would I go about creating it? Any help is appreciate, thank you.
Is This A Good Question/Topic? 0
  • +

Replies To: Setting multiple values to a single cookie?

#2 Dormilich   User is online

  • 痛覚残留
  • member icon

Reputation: 4278
  • View blog
  • Posts: 13,571
  • Joined: 08-June 10

Re: Setting multiple values to a single cookie?

Posted 25 May 2011 - 02:24 PM

$_COOKIE['first_name'] and $_COOKIE['last_name']. Iím not aware that you can save arrays in a cookie.
Was This Post Helpful? 1
  • +
  • -

#3 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3837
  • View blog
  • Posts: 13,997
  • Joined: 08-August 08

Re: Setting multiple values to a single cookie?

Posted 25 May 2011 - 03:14 PM

You could set up your own session handler. That would need to store a session id in a cookie and the id would allow you to retrieve a user's state from your own database. You could store individual values in the database or encapsulate (serialize) a user object and store/retrieve that.
Was This Post Helpful? 1
  • +
  • -

#4 Dormilich   User is online

  • 痛覚残留
  • member icon

Reputation: 4278
  • View blog
  • Posts: 13,571
  • Joined: 08-June 10

Re: Setting multiple values to a single cookie?

Posted 25 May 2011 - 03:26 PM

as far as I remember setting up sessions in your own database neither touches the mechanism PHP handles session cookies nor session data serialisation. that parts are usually done via php.ini
Was This Post Helpful? 1
  • +
  • -

#5 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3837
  • View blog
  • Posts: 13,997
  • Joined: 08-August 08

Re: Setting multiple values to a single cookie?

Posted 25 May 2011 - 03:30 PM

Maybe I'm being too loose with the definition. I'm basically talking about storing user information on the server and leaving a cookie that identifies it. You might store information about their particular setup (their home computer or their iPhone/iPad) and so when they log in you know which they're using and what their preferences are. Not really a session, but I don't know what else to call it.
Was This Post Helpful? 1
  • +
  • -

#6 itdoell   User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 239
  • Joined: 13-January 11

Re: Setting multiple values to a single cookie?

Posted 25 May 2011 - 04:15 PM

View PostCTphpnwb, on 25 May 2011 - 03:30 PM, said:

Maybe I'm being too loose with the definition. I'm basically talking about storing user information on the server and leaving a cookie that identifies it. You might store information about their particular setup (their home computer or their iPhone/iPad) and so when they log in you know which they're using and what their preferences are. Not really a session, but I don't know what else to call it.


Do you mind giving an example so I can see what it is you're talking about? I want to avoid having to set up multiple cookies for information I want to store since I suspect a constant verification confirming the existence of multiple cookies would slow down my script. All cookies would need to be present for information to be displayed correctly, and the ability to delete specific cookies but leave others would cause problems if I were to just verify the existence of a single cookie to speed up the site. Correct me if I'm wrong though as I am not very experienced in this area.
Was This Post Helpful? 0
  • +
  • -

#7 RPGonzo   User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Setting multiple values to a single cookie?

Posted 25 May 2011 - 05:50 PM

You can store a 'array' in a cookie as long as you either serialize it first or use something like json_encode. Or using the array method in the set_cookie function

// straight from the manual
<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
    foreach ($_COOKIE['cookie'] as $name => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name : $value <br />\n";
    }
}
?>



But what CT is talking about would be much better than storing all the user information into a cookie which is controlled by the user and than having your script rely on that information.

He means per user you can set a cookie defining how or from where they are browsing from. And than you can effectively pull the information from your database based on the value of your cookie variable.

This post has been edited by RPGonzo: 25 May 2011 - 05:51 PM

Was This Post Helpful? 3
  • +
  • -

#8 Atli   User is offline

  • Enhance Your Calm
  • member icon

Reputation: 4241
  • View blog
  • Posts: 7,216
  • Joined: 08-June 10

Re: Setting multiple values to a single cookie?

Posted 25 May 2011 - 06:00 PM

View Postitdoell, on 25 May 2011 - 09:16 PM, said:

Is it possible to set a single cookie that can call multiple values?

For example if I wanted to get the client's first and last name could I do $_COOKIE['mycookie']['first_name'] and then $_COOKIE['mycookie']['last_name'] ?

If this is possible, how would I go about creating it? Any help is appreciate, thank you.

You can save array-like cookies -- much like you do with array form variables -- and PHP will automatically translate them into an array for you.

For instance:
<?php
header('Content-type: text/plain; charset=UTF-8');

if (isset($_COOKIE['mycookie'])) 
{
    echo $_COOKIE['mycookie']['one'] . PHP_EOL;
    echo $_COOKIE['mycookie']['two'] . PHP_EOL;
    echo $_COOKIE['mycookie']['three'] . PHP_EOL;
} 
else 
{
    setcookie('mycookie[one]', 'first', 0, '/');
    setcookie('mycookie[two]', 'second', 0, '/');
    setcookie('mycookie[three]', 'third', 0, '/');

    header('Refresh: 0');
}
?>


By naming the cookies using the normal syntax for creating arrays, as you would use it for PHP variables, PHP will translate them into arrays and allow you to access them as such.

Behind the scenes you still have three cookies named as you defined them though. (Important if you plan on sharing these cookies with Javascript.)


What CTphpnwb is talking about -- if I understand him correctly -- is a sort of manual, persistent session handling, where you put whatever info you would otherwise have put into the cookies into a database, identified by a unique ID, and then pass the ID to the cookie. That would allow you to use the ID to fetch the stuff from the database, rather than storing it in the cookie itself.

For example:
<?php
header('Content-type: text/plain; charset=UTF-8');

if (isset($_COOKIE['cookie_id']))
{
    // Fetch the ID from the cookie.
    $cookie_id = (int) $_COOKIE['cookie_id'];
    
    // Fetch the data matching the ID from the database.
    $sql = "SELECT one, two, three FROM my_cookie_data
            WHERE data_id = {$cookie_id}";
    $res = mysql_query($sql) or trigger_error('Failed to fetch cookie data', E_USER_WARNING);
    
    if (mysql_num_rows($res) == 1)
        $myData = mysql_fetch_assoc($res);
    
    // And finally use the data
    echo $myData['one'] . PHP_EOL;
    echo $myData['two'] . PHP_EOL;
    echo $myData['three'] . PHP_EOL;
}
else
{
    // Set some random data to put into the cookie
    $myData = array();
    $myData['one'] = 'first';
    $myData['two'] = 'second';
    $myData['three'] = 'third';
    
    // Construct the query to insert the data
    $sql = sprintf(
            "INSERT INTO my_cookie_data (one, two, three)
             VALUES ('%s', '%s', '%s')",
            mysql_real_escape_string($myData['one']),
            mysql_real_escape_string($myData['two']),
            mysql_real_escape_string($myData['three']));
    
    // Execute, fetch the new ID and put it into a cookie.
    if (mysql_query($sql))
    {
        $new_id = mysql_insert_id();
        setcookie('myCookieID', $new_id, 0, '/');
    }
}


You can also make use of the session_set_save_handler() function, but that's more involved. - The upside there is that PHP will automatically create your session cookie for you.

To be honest, this is not likely to speed anything up, and is a lot more trouble than just using the cookie. Unless you have security concerns, I would avoid this. -- Using a normal session would be just as effective, and a LOT simpler to set up.

This post has been edited by Atli: 25 May 2011 - 06:02 PM

Was This Post Helpful? 3
  • +
  • -

#9 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3837
  • View blog
  • Posts: 13,997
  • Joined: 08-August 08

Re: Setting multiple values to a single cookie?

Posted 25 May 2011 - 06:26 PM

View Postitdoell, on 25 May 2011 - 07:15 PM, said:

Do you mind giving an example so I can see what it is you're talking about? I want to avoid having to set up multiple cookies for information I want to store since I suspect a constant verification confirming the existence of multiple cookies would slow down my script.

I think RPGonzo and Atli have pretty well explained what I was getting at, but I'll try to add more clarity anyway!

Suppose you have users who use your site on their iPhones, Android phones, iPad, and their desktop computers. You might have several settings that they might want to set differently on their different machines such as window and font sizes, whether or not they appear online to other users, etc. Rather than store each setting in a different cookie you might store one id number in one cookie and have that id point to a record in a table that stores all of their settings for that id number/device. Now when they log in you retrieve that one value and use it to look up their preferences. It's a little extra work, but it can be useful, especially for saving information beyond a single session without creating too many extra security issues since all you need to validate is that one cookie.

As far as speed goes, I don't think you'll notice a difference either way.

This post has been edited by CTphpnwb: 25 May 2011 - 06:27 PM

Was This Post Helpful? 2
  • +
  • -

#10 dinojedi   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 26-May 11

Re: Setting multiple values to a single cookie?

Posted 26 May 2011 - 01:40 AM

It os really simple...on 'old' browser a cookie can be long 4096 characters, on modern they can have more than one cookie per site.
Anyway you have to convert all your data into a string.
If is an array use implode(). Choose a separator like | which people not use to write names and lastnames and implode and explode() on demand.
You can also read this value from javascript and use varname,split or varname.join to get/update the vars.
Was This Post Helpful? 0
  • +
  • -

#11 RPGonzo   User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Setting multiple values to a single cookie?

Posted 26 May 2011 - 08:37 AM

View Postdinojedi, on 26 May 2011 - 03:40 AM, said:

It os really simple...on 'old' browser a cookie can be long 4096 characters, on modern they can have more than one cookie per site.
Anyway you have to convert all your data into a string.
If is an array use implode(). Choose a separator like | which people not use to write names and lastnames and implode and explode() on demand.
You can also read this value from javascript and use varname,split or varname.join to get/update the vars.


This method would not be ideal for one main reason, your delimiter cannot always be guaranteed to be unique. Yea you can pick one that would be a 1 in a million shot of being used but there is always a chance.

Using something like serialize or json_encode it essentially flattens your array in a string format, and using json_encode you can still handle this data via javascript easily if you want to.
Was This Post Helpful? 0
  • +
  • -

#12 dinojedi   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 26-May 11

Re: Setting multiple values to a single cookie?

Posted 26 May 2011 - 10:25 AM

View PostRPGonzo, on 26 May 2011 - 08:37 AM, said:

View Postdinojedi, on 26 May 2011 - 03:40 AM, said:

It os really simple...on 'old' browser a cookie can be long 4096 characters, on modern they can have more than one cookie per site.
Anyway you have to convert all your data into a string.
If is an array use implode(). Choose a separator like | which people not use to write names and lastnames and implode and explode() on demand.
You can also read this value from javascript and use varname,split or varname.join to get/update the vars.


This method would not be ideal for one main reason, your delimiter cannot always be guaranteed to be unique. Yea you can pick one that would be a 1 in a million shot of being used but there is always a chance.

Using something like serialize or json_encode it essentially flattens your array in a string format, and using json_encode you can still handle this data via javascript easily if you want to.


I didn't insert the code to clean up things because is obvious that using str_replace you can always get rid of unwanted chars.
Another idea is to convert the entire string using base64_encode.
Serializing things make complex simple things, also to use JSON on PHP is not easy!
Was This Post Helpful? 0
  • +
  • -

#13 RPGonzo   User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Setting multiple values to a single cookie?

Posted 26 May 2011 - 10:54 AM

JSON is simply a format using it in PHP is as easy as using json_decode on the presumed flattened array and working with it as a normal array.

<?php

$data = array(
	'firstname' => 'My First Name',
	'lastname' => 'My Last Name'
);

if (!isset($_COOKIE['mycookie'])) {
	// create the cookie with our array value
	setcookie("mycookie", json_encode($data));
}

echo "Our data variable contains:";
foreach ($data as $k => $v) {
	echo "$k == $v<br/>";
}

echo str_repeat("_", 150) . "<br/>";

if (isset($_COOKIE['mycookie'])) {
	echo "Our cookie contains:";
	// our cookie is encoded
	$cookie_data = json_decode($_COOKIE['mycookie']);
	foreach ($cookie_data as $k => $v) {
		echo "$k == $v<br/>";
	}
} else {
	echo "No cookie data set!!<br/><br/>";
}

?>



This will simply set a array into a cookie on the first page load, on the second page load because the cookie is set it will grab the data decode it and work with the data as a array in a foreach loop. I'm not sure how I can understand that is difficult.

if you want to put that into a basic javascript array for use later simple give your cookie data to a javascript var.

<script type="text/javascript">
	var json_data = <?php echo isset($_COOKIE['mycookie']) ? $_COOKIE['mycookie'] : '{}'; ?>;
	
</script>

<button onclick="alert(json_data.firstname);" >Show First Name</button><br/>
<button onclick="alert(json_data.lastname);" >Show Last Name</button>



and when you click the button it will show you your first name, or your last depending on which you click.

EDIT:: The reason you don't have to decode the data for javascript is because it sees the format of the json_encode as a object. Hence the use of jason_data.varname

This post has been edited by RPGonzo: 26 May 2011 - 11:15 AM

Was This Post Helpful? 2
  • +
  • -

Page 1 of 1