Session variables seem not to be saved - php

Quite simple code:
<?
session_start();
$_SESSION['t'.time()] = "ok";
echo "<pre>".print_r($_SESSION, 1)."</pre>";
?>
shows, as expected, something like
Array
(
[t1330966834] => ok
[t1330966835] => ok
[t1330966836] => ok
)
after 3page reloads.
Let's change a few symbols:
$_SESSION[time()] = "ok";
(now without 't') and I expect after few reloads something like
Array
(
[t1330966834] => ok
[t1330966835] => ok
[t1330966836] => ok
[1330967020] => ok
[1330967021] => ok
[1330967022] => ok
[1330967023] => ok
)
But actually the result is absolutely different:
Array
(
[t1330966834] => ok
[t1330966835] => ok
[t1330966836] => ok
[1330967020] => ok
)
We have 3 previous array cells ad one and only one 'time' cell - no matter how many times you reload the page. The time is correct, it different each second but only one cell without 't'!
Also I tried
$t =time();
$_SESSION[$t] = "ok";
and even
$t =intval(time());
$_SESSION[$t] = "ok";
But it's remains only one cell with time.
Tested at php 5.2.13 and 5.3.10 at 2 different servers.
What am I doing wrong?

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. For more details see the section on variables in this manual.
http://php.net/manual/en/session.examples.basic.php

When cranking error_reporting way up, you should notice this:
Notice in <file>, line ...: session_write_close(): Skipping numeric key 1330967020
Numeric indeces to session variables are not supported.

This is not a strange thing. It is simply skipping numeric keys. You can see this error, if you have enabled the notice to be displayed.
As mentioned on this comment on php.net. You should not use numeric keys to define values in session.
Quote
Careful not to try to use integer as a key to the $_SESSION array (such as $_SESSION[0] = 1;) or you will get the error "Notice: Unknown: Skipping numeric key 0. in Unknown on line 0"

Related

Codeigniter, array in session, change the value of array in session in a specific key

I have a variable in session that contains array of numbers. I want to change a specific number inside that variable.
My session:
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true,
// 20 slots, the counting starts from 0, the last slot's position
// is 19.
'slots_id' => array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
);
So, slots_id is the variable that i want to access. I need to change the last number, it.In my controller i have the following.
$this->session->set_userdata('slots_id'[19], 100);
Here i'm trying to set the last slot's value to 100. But the "[19]" that i put there causes error.
A PHP Error was encountered Severity: Notice Message: Uninitialized string offset: 19
Google did not help me in my current situation, thank you for your time.
Two ways around your problem:
$this->session->set_userdata('slots_id'[19], 100); is not attempting to assign a value of 100 to the array element on index 19 for the $slots_id array. It's trying to set a value of 100 as the 20th character (index 19) of the 'slots_id' string, which goes out of bounds.
You may try:
$this->session->set_userdata('slots_id[19]', 100);
Or even better, remove the full element from session, update it and reset it:
$aux = $this->session->userdata('slots_id');
$aux[19] = 100;
$this->session->unset_userdata('slots_id');
$this->session->set_userdata('slots_id', $aux);
it's a bit more code, but my advice would be to always replace session data rather than update it on the fly.
Uninitialized string offset errors in PHP have a vast amount of documentation around them. You are getting this error because you are not referencing index 19 of an Array, you're referencing it of a string, which is exactly what 'slots_id' is in this instance. 'slots_id' is 8 characters long which means any index beyond 7 is in fact undefined.
If you have no direct access to the $_SESSION superglobal for some odd reason, you need to retrieve the entire slots_id array via the helper, update the index you need in your local copy, then update the session variable's slots_id array with your updated copy.

how to read string in Array ([2622232] => [] => apple ) PHP

I am trying to read string in session array.
Here is the code I entered $fruit_type into my session:($number is 2622232 here)
$_SESSION['fruit'][$number]=$fruit_type;
When I used print_r($_SESSION['fruit']), I get the following array:
Array ( [2622232] => [] => apple )
My question is how can I get the string "apple"? My editor give me error message when I tried to use $_SESSION['fruit'][$number][] to read string.
Any idea about my situation?
The only way to get that print_r() output is with an empty string as key [''], so you need to find where you do that and fix it. However you can access it:
echo $_SESSION['fruit'][2622232][''];
$_SESSION['fruit'][$number][] is wrong as you don't pass an index. Something like $_SESSION['fruit'][$number][0] should work.
You can find more information about arrays in the PHP documentation (here the example that solves your problem)

PHP array of unknown length with 0 as initial value

I have PHP $_SESSION arrays that have an undefined amount of elements. Is it possible to initialise all the values to 0, or do I have to check whether the value is NULL and then set to 0 every time I check a value?
Edit: I'm sorry for the vagueness of my question.
I have an undefined amount of levels, and I'd like to store all the scores of each level in that array. Currently my amount of levels is fixed, so I am currently just writing:
$_SESSION['totals'] = array(0,0,0,0,0);
And then when adding manipulating the data, I simply increment/add a certain amount to that element.
Now I'd prefer to have the same ease of directly incrementing/adding values to certain elements without needing to check whether a value is NULL or something like that...
Edit 2: edited my code as follows:
$_SESSION['totals'] = array();
if(array_key_exists($row['level']-1,$_SESSION['totals'])){
$_SESSION['totals'][$row['level']-1]++;
}else{
$_SESSION['totals'][$row['level']-1] = 1;
}
And it seems to work. Thanks fellas!
You can use array_fill_keys function to fill an array with specified value for defined keys:
$keys = array('foo', 'bar', 'baz');
$output = array_fill_keys($keys, 0);
Defining an array with initial values is defining an array with a length. This does not prevent you from adding or removing elements from the array:
// initial array
$myArray = [0, 0, 0, 0];
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0)
$myArray[] = 1;
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 1 )
$_SESSION contains only what you put into it. Just make sure you add 0 instead of null the first time you add something.
If you need to do this later, I think your design might be bad. But anyway, $_SESSION is like a normal array, so you can just use PHP's array function to traverse the array and check or change each value.
PHP arrays aren't really arrays you might know from other languages. They really are more like linked lists with hash access.
What this means is: You either know all the string array indices you want to use, and either make sure they exist, or you check their existence every time you access them which might fail.
For numeric indices, the same thing applies. You might have an array with indices 1, 2 and 4 present, but if you run over it with only a for loop, you will trigger a notice when accessing the nonexistant element 3.
Use foreach loops whenever you want to iterate arrays. Check with isset() whenever you want to document that the array value might not be present. Don't do it if you know or assume that the array element MUST be present - if not, you get the notice as a reminder that your code is working on a data structure that is NOT what you thought it is. Which actually is a good thing. Then fix it. :)
Your best bet would be to abstract your session stuff by creating facade methods, or getters and setters around the session variables rather than access them directly. This way you can return a default value if the one you're after doesn't exist.
I've used array_key_exists() to check if the index is set. If it is not, I display 0 or add store a certain value in that field, else I show the value of that index or add certain value to that field.
Credit to Sven for bringing that up.
to check what u have in your sessions, loop tru it. not sure if this is what u are asking.
foreach($_SESSION as $x=>$y)
{
if(empty($x)) { //do something }
}

CakePHP returning double array from find('list) query

I'm using cakephp and am getting back a "double array" where it is giving me 2 arrays where it should be 1, I have looked into the issue as far as cakephp and can't figure it out and just want to move past this for now so I am wondering if anyone knows how to unset a second array if a variable has 2 arrays.. below is the print_r of the array, its just one variable that has this, which I find odd.. so I want to make it so there is not a 2nd set of duplicate values, if I do an array_push it pushes both values for that index into the resulting new array index so that won't work
one variable is equal to the following:
Array ( [0] => 42 [1] => 62 ) Array ( [0] => 42 [1] => 62 )
EDIT:
This is not an issue of my printing out the array twice accidentally, as I said above, with a foreach array_push of the variable, i end up with this, which is odd:
Array ( [0] => 4242 [1] => 6262 )
EDIT:
This is the cakephp database call that I am using, I know I didn't ask this in regards to cakephp but since some people think this is impossible i am posting this just so you can see what it does if you want
$specificfields_array = $this->Mymodel->find('list', array('fields' =>'Mymodel.id'),
'conditions' => array('emailgroup' => $categorynumber, 'sent' => '0');));
EDIT:
This is what a "foreach" array_push is:
$mynewarray = array();
foreach ($specificfields as $specificfields_current) {
array_push ($mynewarray, $specificfields_current);
}
A variable cannot "have two arrays". It can be one array that has two arrays nested. The scenario you describe is impossible (probably there are two print_r there or there is a < character hiding stuff – check the HTML source).
Can you post the controller, the model and the view file with your print_r calls to the http://bin.cakephp.org/ site and post the links back here so we can see all of your code?

Array call from key not working correctly

I'm trying to call to a specific part of an array with the key # and it's not working. I can output the array and see it...
Array
(
[6] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
[7] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
[8] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
)
This array is $emailDB. I can call to the array manually with $emailDB[7] and it works, but if my call is dynamic like this it won't work...
<?php
$value = 7;
print_r($emailDB[$value]);
?>
I've never had an issue like this with an array so it's very odd. What really sucks is I'm under deadline with a form not working on a client's site...joy.
We tried this with no luck...
<?php
$value = 7;
print_r($emailDB[intval($value)]);
?>
I thought intval() would assist but it did not.
You're post implies a bug in php itself, which I highly doubt. What's more likely is that what you posted doesn't properly represent the code you're running.
Why don't try this. Make a brand new empty php file. Hardcode the array keys and values and assign them to the $emailDB variable, and then try
$value = 7;
print_r($emailDB[$value]);
You will see you don't have the problem that you claim. You have now started the debugging process, and now you can look at the working, and non working code to compare the difference.
Well, you are echoing an Array, which I assume is printing "Array" onto your screen. If you want to echo the actual contents of the array, you need to use print_r($array) or echo print_r($array, true). You can also try putting the value in quotes, like $emailDB["{$value}"] to see if that works, I sometimes have troubles with integers not going into things properly.
I agree with you all. It had to have been something whacky with how we were pulling in the data somehow. It was a tab-separated file we were exploding. I just re-wrote the whole thing entirely and imported the data into MySQL and all was well.
In hindsight, I have a sneaking suspicion it was a trim() command that was needed and likely nothing more. Dang it...too late, but I learned something about checking over the code for those types of things.

Categories