Best way to store form values in PHP Cookie? - php

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.

Related

PHP Session Variable not Available

I have a PHP file (approvals.php) that only gets executed on an AJAX call. It has a postgresql query that searches a table and uses a customer id, which is set as a session variable. Problem is, it seems I can't access this session variable in this file. My query is like:
$query = "SELECT merchant_id FROM ndovu_merchant_users WHERE customer_id={$_SESSION['customer_id']}";
$result = pg_query($query);
I have tried to echo the session variable $_SESSION['customer_id'] but nothing. However on passing a fixed value to the query, it returns a result.
In your case, i would have checked if the session is set in the first place.
//this should be put at the header of the page
session_start();
if(isset($_SESSION['customer_id']) && !empty($_SESSION['customer_id'])){
echo $_SESSION['customer_id'];
}else{
echo 'session is not set';
}
You need to place session_start(); above the code section where you use it; the top of the page is usually the best place to place it.
Also, it should be noted; you have what is potentially a large security flaw here, by passing in unescaped data.
You should look into using prepared statements if possible; or at least escape your inputs.
The user session is not accesed when the script is called by an ajax request.
The session token wich php requires to obtain the session data is stored in the client side(user) inside a session cookie.
You can read more here
https://stackoverflow.com/a/1535712/3922692
Just pass the user id with GET or POST in the ajax request.
There is not enough code presented but if you realy need to get the id from the session you can use an iframe (which is not recommended), process fetch data server side and output it in the iframe.

Save Constant GET Variable In A Session

Can some explain to me the best way to store a $_GET variable in a session and the only way the sessions changes is when we verify the data the session is being change to is different from the GET variable.
Currently i have
$tid = clean_get($_GET['tid']);
in a global file which is included on every page the problem with that is the value of $tid will be erased and not stored in a session like i want it to once the user is not on a page with $tid set in the url.
If you get $_GET['tid'] in url then set session again by that new value otherwise restore it from session. Thats it.
session_start();
$tid = (isset($_GET['tid']) && $_GET['tid']!="") ? clean_get($_GET['tid']) : $_SESSION['tid'];
Try this and tell me is it solved?
Use a function like isset() to see if it is being sent. Only then should you replace it:
if(isset($_GET['tid']))
{
$tid = clean_get($_GET['tid'])
// Do stuff to change session data.
}
I think what you are looking for is something like
session_start();
foreach ($_GET as $key=>$value) {
$_SESSION['getValues'][$key] = clean_get($value);
}
This will store all the values in $_GET in the $_SESSION. To retrieve the values later, you just have to use $_SESSION['getValues']['tid'] after calling session_start().
Here I'm assuming that clean_get() is just something that formats and/or escapes data that came in from forms, so calling it on each value before sticking into the session will do all that cleaning when needed.
Note: only call session_start() once, and make sure you do so before doing anything with $_SESSION, otherwise you'll get error messages.

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

Using PHP $_COOKIE to manage session vars

Due to server settings I am having to use $_COOKIE instead of $_SESSION to manage session vars for a project.
On my search form I set an initial cookie but am unclear whether this is helpful or needed?
setcookie('NOSG', 'oHai', time()+7200, '/', 'some.org');
Each time the search results page loads I iterate over the cookies and back date the ones I need to clear and then set the new values like so:
if ($board) {
foreach ($_COOKIE as $k => $v) {
if (preg_match('/boa_/', $k)) {
setcookie($k, '', time()-3600, '/', 'some.org');
}
}
foreach ($people as $p) {
setcookie('boa_'.$p->ID, $p->whatever, time()+7200, '/', 'some.org');
}
}
Mostly this is used for making sticky selections in multi-line <SELECT> inputs.
Is this approach sound? I have rarely used $_COOKIE for anything.
// EDIT 1:12 PM GMT-06:00
All of the comments and answers are focused on fixing sessions. I assume this is because there is some reason the method suggested is NOT sound? The question asked is about using $_COOKIE to remember form settings. Would anyone care to respond as to why the method I am using is or is not appropriate to the problem?
The error
Permission denied. session.save_path is set to /var/lib/php/session PHP Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0
Is due to an error on the part of your host/system administrator. They should set the permissions on /var/lib/php/session to 777 so it is writable by all users. If they are using something that executes your PHP script as your user, the data is still safe because your user will own the session data file so no one else can view or modify it.
Alternatively, you can change the session save path on the fly to a directory under your control.
If you were to have a common file that initiated your session, add this before session_start():
session_save_path('/home/yoursite/sessions');
// or
session_save_path($_SERVER['DOCUMENT_ROOT'] . '../sessions');
// or, an alternate method
ini_set('session.save_path', '/home/yoursite/sessions');
session_start();
Then just created that folder and set the permissions appropriately so it is readable/writable by your user only.
Technically all a session is, is a text file (OK, you can hold the data in a database as well) containing variables that's identified by a value held in a cookie (or the address bar).
It wouldn't be impossible to recreate the functionality within PHP using things like setcookie(), serialize() and file_put_contents() writing to a folder outside the web tree ... though you might also need a Cron job to schedule garbage collection (to be fair, PHPs native session GC doesn't seem to be spectacular).
You'd just need to create a custom session handling object and set the "session" id for it in a cookie exactly the same as if you were using normal session handling - except instead of using $_SESSION you'd use you Session::get() and Session::set() methods.
If you keep the API clean then, at a future date if you manage to get session handling enabled on the server, you'd only need to tweak your session handling object and it wouldn't affect the rest of your program code - it's probably a good idea to abstract away then session handling anyway.
None of the respondents addressed my question: Is using $_COOKIE to store session data a sound method?
Experience has taught me what they would not. Not all browsers handle cookies in the same way. For instance Internet Explorer has limits per domain on the number of cookies: http://support.microsoft.com/kb/941495
So the answer is- $_SESSION is superior to cookies as it is handled by PHP in the same manner for all browsers.

How to assign multiple dimensional array in cookies with 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.

Categories