How to assign multiple dimensional array in cookies with PHP? - php

cookie[person][name], cookie[person][id], cookie[person][age]
How to make the cookie like above?

Well, you could assign the value of the cookie to be a serialized array
$array = array("person1" => array("name" => "Ted"));
$value = serialize($array);
set_cookie("name", $value);
When you want to read it back, get the data from the cookie and unserialize it
$array = unserialize($_COOKIE['name']);
That probably wouldn't hide the data you are trying to store very well. The other situation is to use a Session variable instead
session_start();
Now you can assign anything you want, arrays, objects, anything to $_SESSION.
$_SESSION['person'] = array();
The session variable is very similar to an array, but the data is actually stored in a file, and the id of the user is stored in a cookie. PHP matches the ID on the cookie with the file, and when you hit session_start(), populates the superglobal with the files contents.
This means that objects you make will end up being serialized.
Either way, it is the same basic idea. You serialize a data structure, write it to a file (cookie or session file) and read it back later.

Related

What data can be accessed through the $_SESSION superglobal

I had this question in a quiz:
Once a session is started, all data related to the session is accessible through the $_SESSION superglobal.
A. True
B. False
My answer was false, because I thought only the data stored explicitly like this: $_SESSION["something"] = "something", is accessible.
But I the correct answer was true.
So, what else can I get from this superglobal? Or maybe it's just the wording issues, the actual question was asking everything in this session stored like this can be accessible?
$_SESSION superglobal may be to use only with session. When you pass data with session also, you can get data with it. Data types can be string, int,float,array etc.
For example:
<?php
// Start new or resume existing session.
session_start();
// Add values to the session.
$_SESSION['item_name'] = 'value'; // string
$_SESSION['item_name'] = 0; // int
$_SESSION['item_name'] = 0.0; // float
// Get session values.
$value = $_SESSION['item_name'];

Using PHP session_decode() without adding the session variables to own session

I have a PHP script that uses session_decode to get the session variables of customer's session (from session stored file).
The problem is that whenever I call the script and it reads the session variables, it also add them to my own session. Is there a way to avoid this or maybe use a better method to get the customer's session information without using session_decode?
Thanks
I think I have found the simplest solution/workaround:
<?php
// if session is not started
session_start();
// store our current session
$my_sess = $_SESSION;
// decode $data (the encoded session data, either from a file or database). Remember, decoded data is put directly into $_SESSION
session_decode($data);
$data = $_SESSION;
print_r($data);
// restore our own session
$_SESSION = $my_sess;
?>

Best way to store form values in PHP Cookie?

After a form submission I would like to store several specified form values in a PHP cookie. I need the data to persist after the browser is closed so I don't want to use sessions. My current call looks like this:
if ($_GET) {
$params = $_GET;
}
Is there a way to set several params from $_GET to a $_COOKIE so I can use them later when the user returns?
You can still use sessions for you problem. Just change the cookie parameters with session_set_cookie_params() (see here) to a time > 0 (0 implies that it should be deleted when the browser is closed) and increase the session cache lifetime with session_cache_expire() (see here).
This has the advantage that even data that the client shouldn't be able to change cannot be changed by simply changing the cookie on his machine.
Cookies only
The other approach could include some serialization (e.g. use serialize() and deserialize() or do something on your own for things of low complexity like simply joining some arguments with a delimiter) of your parameters directly stored into a cookie with the setcookie() function. Get more info about that here. With that you can read out the cookies values directly from the superglobal $_COOKIE.
Check the PHP documentation for setcookie: http://php.net/setcookie
You can use serialize(), or do a foreach() loop of all $_GET values, and set those in the cookies (different cookie for each value)
you can use foreach to traverse through GET array and set the cookies with their index names.
try this -
$expire=time()+60*60*24*30;
foreach($_GET as $k=>$v){
setcookie($k,$v,$expire);
}
This will set cookie names same as GET array indexes and will be expired after a month.

PHP Session Not Restoring from Cookies

When a user returns to my website, it attempts to restore their last session from the $_COOKIE associative array. It's not working as expected. I can look in my browser's cookie manager and see that the cookies are there, but they don't seem to be getting saved to the $_SESSION associative array.
This is essentially the program flow when a user returns to my site:
foreach ( $_COOKIE as $name => $val )
{
$_SESSION[$name] = $val;
}
session_start();
...
$some_var = $_SESSION[$var_name];
Do I have things out of order, or should I not be overwriting PHPSESSID? Any insight as to what I'm doing wrong would be appreciated. Thanks.
You're getting sessions and cookies mixed up. You don't need to put things into the $_COOKIE array. Just use session_start() and then put things into $_SESSION. PHP will automatically then manage the session/cookie for you.
$_COOKIE variables are stored on the users browser, so they aren't secure and can be manipulated by the user => security risk.
$_SESSION variables are stored only on the server. The only thing stored in the cookie is a session_id, so $_SESSION variable can't be manipulated.
Does that make sense?
Put session_start() before anything else; this function initializes the session data that you will be accessing in $_SESSION.
Not exactly sure what you're trying to achieve with the rest of it all, but session_start() first is a starting point...

PHP: Over-writing session variables

Question related to PHP memory-handling from someone not yet very experienced in PHP:
If I set a PHP session variable of a particular name, and then set a session variable of the exact same name elsewhere (during the same session), is the original variable over-written, or does junk accumulate in the session?
In other words, should I be destroying a previous session variable before creating a new one of the same name?
Thank you.
$_SESSION works just like any other array, so if you use the same key each time, the value is overwritten.
Tom,
It depends on how you use the session variable, but it generally means "erasing" that variable (replacing the old value by the new value, to be exact).
A session variable can store a string, a number or even an object.
<?php
# file1.php
session_start();
$_SESSION['favcolor'] = 'green';
$_SESSION['favfood'] = array('sushi', 'sashimi');
?>
After this, the $_SESSION['favcolor'] variable and the $_SESSION['favfood'] variable is stored on the server side (as a file by default). If the same user visit another page, the page can get the data out from, or write to the same storage, thus giving the user an illusion that the server "remembers" him/her.
<?php
# file2.php
session_start();
echo $_SESSION['favcolor'], '<br />';
foreach ($_SESSION['favfood'] as $value) {
echo $value, '<br />';
}
?>
Of course, you may modify the $_SESSION variable in the way you want: you may unset() any variable, append the array in the example by $_SESSION['favfood'][] = 'hamburger'; and so on. It will all be stored to the session file (a file by default, but could be a database). But please beware that the $_SESSION variable acts magically only after a call to session_start(). That means in general, if you use sessions, you have to call session_start() at the beginning of every page of your site. Otherwise, $_SESSION is just a normal variable and no magic happens :-).
Please see the PHP reference here for more information.

Categories