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.
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 have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);
I'm trying to set session in my program, after the user has logged with his account. If user input good email and password, then program set some variables, like this:
$_SESSION['user']['id'] = $row['id'];
$_SESSION['user']['email'] = $email;
$_SESSION['user']['admin'] = $row['admin'];
$_SESSION['logged'] = true;
The problem is, that I'm getting this warning from first three rows of code above:
Warning: Illegal string offset 'id' in C:\Program Files (x86)\Zend\Apache2\htdocs\OOPeshop\user\User.php on line 193
So I checked, if all the variables are set, so i add to my code this two lines:
var_dump($row);
var_dump($email);
but it was looking alright, I was getting output
array(2) { ["id"]=> string(2) "14" ["admin"]=> string(1) "0"}
string(22) "foobar#gmail.com"
So can someone explain me where is the problem? I checked similar question, but found no solution to my problem.
I have tried this:
$user = array('id' => $row['id'], 'email' => $email, 'admin' => $row['admin']);
$_SESSION['user'] = $user;
No more warnings. It set array first and then set whole array to session variable, it worked, but i don't know where's problem in my first code, so maybe someone with better understanding can explain it better.
I have tried this:
$user = array('id' => $row['id'], 'email' => $email, 'admin' => $row['admin']);
$_SESSION['user'] = $user;
No more warnings. It set array first and then set whole array to session variable, it worked, but i don't know where's problem in my first code, so maybe someone with better understanding can explain it better.
It seems that $_SESSION['user'] has been in somehow set to string, dont know why, but that's the only explanation.
This type of error can be couse of attempt to access an array index using an object or an array as the index key. Check whether your array is proper.
Try this:
Somewhere in the begininig of your code
if(!isset($_SESSION['user'])){
$_SESSION['user'] = array();
}
Then you can continue adding elements for $_SESSION['user'] as you did ( $_SESSION['user']['id'] = ... )
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'];
Eg:
$_SESSION['1'] = 'username'; // works
$_SESSION[1] = 'username'; //doesnt work
I want to store session array index as array index. So that o/p is :
Array(
[1] => 'username'
)
$_SESSION can only be used as an associative array.
You could do something like this though:
$_SESSION['normal_array'] = array();
$_SESSION['normal_array'][0] = 'index 0';
$_SESSION['normal_array'][1] = 'index 1';
Personally, I'd just stick with the associative array.
$_SESSION['username'] = 'someuser';
Or
$_SESSION['username_id'] = 23;
I suspect this is probably because the $_SESSION array is purely an associative array. Additionally, as the PHP manual puts it:
The keys in the $_SESSION associative
array are subject to the same
limitations as regular variable names
in PHP, i.e. they cannot start with a
number and must start with a letter or
underscore.
Incidentally, have you checked your error log for any NOTICE level errors? (You may have to enable this level.) Attempting to use a numeric key will quite possibly raise an error.
You can also take this approach to save an array dimension:
$_SESSION['form_'.$form_id] = $form_name;
which might look like the following:
$_SESSION['form_21'] = 'Patient Evaluation';
as opposed to:
$_SESSION['form'][21] = 'Patient Evaluation';
which uses another array dimension.