my script currect have two session called
$_SESSION['mypic']
and
$_SESSION['mypicsrc']
can I combine this two to one session and sub-session?
like this:
$_SESSION['mypic']
$_SESSION['mypic']['src']
the $_SESSION global is an array that will only store strings. If you want to store an array inside a $_SESSION var you have to serialize it first
$data = array( 'src' => '' );
$_SESSION['mypic'] = serialize($data);
then to get it back out you have to deserialize
$data = deserialize($_SESSION['mypic']);
However, you should store your data in a database and then store an id or reference to that particular record in $_SESSION.
Actually, you only have one session there, with the values stored in $_SESSION.
You can change them like any other variable;
$_SESSION['mypic']['src'] = $_SESSION['mypicsrc'];
Related
I'm trying to create a php to do list using cookies, however am struggling to store the cookie inside an array so that I can add more than one cookie.
When I submit the form, a cookie is added, but when I go to add another the first one is replaced.
I want to store the cookie in a variable, push it to an array then save it to the end of the list rather than replace the current cookie.
Here is the code I have so far:
if (isset($_POST['submit'])) {
$task = htmlentities($_POST['task']);
$tasks = array ();
if(isset($_COOKIE[$task])) {
array_push($tasks, $task);
echo $_COOKIE[$task];
} else {
}
setcookie('task', $task, time() + 3600);
header('Location: index.php');
}
I'm not sure on exactly where I'm going wrong, would anyone be able to help?
When you store a cookie with the same name, it gets overwritten. You also seem to be storing the individual task and not the array. If you would like to store the array safely, you can attempt to store it as JSON.
It would look like this:
if (isset($_POST['submit'])) {
$task = htmlentities($_POST['task']);
//Check if the cookie exists already and decode it if so, otherwise pass a new array
$tasks = !empty($_COOKIE['tasks']) ? json_decode($_COOKIE['tasks']) : [];
//if(isset($_COOKIE[$task])) {
array_push($tasks, $task);
// echo $_COOKIE[$task];
//}
$encodedTasks = json_encode($tasks);
setcookie('task', $encodedTasks, time() + 3600);
header('Location: index.php');
}
You seem to be checking if the value of the post variable is a key in your array rather than using the 'tasks' key as you set in your setcookie. You do not need to see if the array exists again as you passed either the decoded array or the empty array as 'task'
There are a few things wrong with your code. First of all, you cannot story an array in a cookie, only strings. Whay you can do is transform your cookie to JSON when setting it, and when you are getting it decode it. Also, when pushing to you array, the array you are pushing to is reset on every request. To get around this, first get you data from the cookie. Something like this is what I would use:
const COOKIE_NAME = 'tasks';
$tasks = ['one', 'two'];
setcookie(COOKIE_NAME, json_encode($tasks));
$newTask = 'another task';
if (isset($_COOKIE[COOKIE_NAME])) {
$tasks = json_decode($_COOKIE[COOKIE_NAME], true);
array_push($tasks, $newTask);
setcookie(COOKIE_NAME, json_encode($tasks));
}
var_dump(json_decode($_COOKIE[COOKIE_NAME], true)); // Every request after the first time a cookie is set "another task" is added to the cookie.
I am not sure if it's possible or not but I am trying to pass a random variable to fill an array.
Here is the code normally:-
//Loading all data of user in an array variable.
$user_fields = user_load($user->uid);
// Updated one array variable in this array.
$user_fields -> field_module_3_status['und'][0]['value'] = "Started";
// Saved back the updated user data
user_save($user_fields);
But I want to provide the variable field_module_3_status dynamically through a variable.
Hence suppose I have $user_field_name = field_module_3_status.
So what I tried to do is:-
$user_fields = user_load($user->uid);
$this_users_status = $user_fields -> $user_field_name;
$this_users_status['und'][0]['value'] = "Started";
user_save($user_fields);
Unfortunately this doesn't work.
Any idea how I can achieve this?
You're making a copy of the array when you do the assignment to $this_users_status. You need to assign to the array in the object property.
$user_fields->{$user_field_name}['und'][0]['value'] = "Started";
Or you could use a reference:
$this_users_status =& $user_fields->$user_field_name;
My session array looks like the following:
$_SESSION => array(
"acc"=>array(
"name"=>"Account name",
"id"=>1,
...
),
"name"=>"User name",
...
);
To clarify, please note that this is just to show the format. I am not actually setting $_SESSION to a new array. For that code, please see the end of the question.
If I dump the $_SESSION, I get just what I expect; however, if I try to reference one of the "acc" variables that has the a key that is used in the parent session array, it will give me the result stored in the session array.
For instance
$_SESSION["acc"]["name"]
This returns "User name", when it should return "Account name".
Why is this?
If I set the acc variable key to something else, like aname, e.g.
$_SESSION["acc"]["aname"]
This returns "Account name" like it should.
Session creation code:
session_start();
$acc = array(
"id"=>$accid,
"sub"=>$sub,
"name"=>$name,
"exp"=>$exp
);
$_SESSION["acc"] = $acc;
$_SESSION["admin"] = $admin;
$_SESSION["name"] = "$fname $lname";
$_SESSION["uid"] = $uid;
This appears to be a bug. After messing around with key names, I found that after changing the key names and undoing my changes to make the key names the same again, it worked, but after doing it again, it didn't.
Because $_SESSION is already an array when you write $_SESSION = array (.... You created array of array.
hi
this is pushan
I am using $_SESSION['name']='the 2d array name', to assign a dynamically created 2d array to a session variable in php.when I am accessing the session variable in the other page anfd printing the values only the values of the last row of the 2d array is getting printed . the rest is all blank.Please help me I am under tremendous pressure.
thanks
It looks like you assign only a string to the session variable. But you have to assign the array itself:
$_SESSION['name'] = array(...);
// or a reference of the array
$_SESSION['name'] = $array2;
You can use serialize() to save the array to the session as a string, then unserialize() to recover it later.
Page 1:
$_SESSION['name'] = serialize($arrayName);
Page 2:
$arrayName = unserialize($_SESSION['name']);
var_dump($arrayName);
How can i store multiple values for a variable in cookie using php, for example
$id = 1,2,4,5
Then how can i compare the stored values with a variable? for example, $new_id=4, i want to check if $new_id value exists in the stored values of $id in cookie.
Thanks for help and have a nice day.
You can store arbitrary strings in cookie elements, so a serialized array should work. Example:
// To store:
$ids = array(1, 2, 3, 4);
setcookie('ids', serialize($ids));
// To retrieve:
$serialized = $_COOKIE['ids'];
$ids = unserialize($serialized);
// sanity check: $ids needs to be an array.
assert(is_array($ids));
// Now let's check:
if (in_array(4, $ids)) {
// Yes, it's here.
}
A few caveats though:
The cookie is completely in the hands of the client, and cookie values should never be trusted. Treat them just like you would treat query string parameters or POST data.
Cookies offer very limited storage (IIRC, the standard gives you 4096 bytes to work with).
With these in mind, it might be a better idea to store the array in $_SESSION instead - this will give you virtually unlimited storage, and the only way for the client application to fiddle with the values is through your code.
Try with following snippet.
// do Stuff to retrieve value of $id from cookie.
// explode variable to array
$idArr = explode(',' , $id);
// check existence of new_id in cookie variable.
if(in_array($new_id , $idArr)){
// new_id exist in cookie variable
}
Hope this will help
Thanks!
Hussain.
to use the multiple value you can use the array and then to store it you can serialize ( and unserialize) the array.
To create array: $array = array(1,2,3,4);
To compare: if (in_array(2,$array)) echo "Yep";
To serialize the data to be stored: $store = serialize($array);
Ten you will be able to create the cookie with $store data and then use unserialize($store) to reconvert data in array.
Serialize Manual
Store array in cookie and then compare them
Here is one out of many solutions (syntax may contain errors):
// Create an array with the values you want to store in the cookie
$id = array(1, 2, 3, 4);
// Create cookie
set_cookie('id', implode(',', $id));
// Get cookie
$id = explode(',', $_COOKIE['id']);
// Test value
if(in_array($newId, $id) === true) {
// Value is in the array
}
Restrictions:
The values stored in $id cannot include commas, choose another separator if you need to store commas