PHP sessions acting weird, current object appears in _session - php

I have the following code:
<?php
session_start();
class Cinstaller {
function CInstaller() {
$this->templates["x"] = "";
}
function DoEvents() {
if ($_GET["x"]) {
$_SESSION["install"] = $_GET;
}
}
}
$install = new CInstaller();
$install->DoEvents();
print_r($_SESSION);
?>
On a certain server ( first time when i see something like this ) Php 5.2.17, running as CGI/FastCGI, it acts werid.
When i run test.php?x=y I get the following dump:
Array
(
[install] => Array
(
[x] => y
)
)
When I go back and I run test.php without any other parameters I get the following:
Array
(
[install] => Cinstaller Object
(
[templates] => Array
(
[x] =>
)
)
)
How the heck the string variable "install" from session turned into the object from current file ?

Note : OK..! Seems like you may be having some sort of other problem but as you said that changing names of variable and session solved your Problem so in order to consider this question solved..! Here I am going to post the same answer..!
Solution :
You should change your Variable and Session names to fix this problem there may be some sort of conflict at your server with use of same name for variable & Sessions..!

If you do:
$_SESSION["install"] = $_GET;
You will put on "install" session all content that you got by $_GET and the value of session will be an Array().
If you want jut the value of parameter "x" that was sent using GET method, try this:
$_SESSION["install"] = $_GET["x"];
And only the value of the "x" parameter will be in the session. Also, filter the value that you get by url:
$_SESSION["install"] = filter_var($_GET["x"], FILTER_SANITIZE_STRING);

Related

PHP: `strcmp` serialization of identical object and array failing

I have a legacy app where i am trying to migrate changes from the old into the new while generating a log of changes. Things are going well; however, I keep running into "changes" that change nothing. After digging into this, I found that the legacy code is using arrays and the new code is using objects. If serialized, I thought they would be identical. After all, if they are dumped via print_r they are identical. But that is not the case. Even more astounding, the objects keep their integer keys even after serialize-unserialize cycling them.
The request is: how can I show these two strings are identical since their resulting object/array is identical save for key typing.
<?php
$v3v = 'a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}';
$v4v = 'a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}';
$v3 = unserialize($v3v);
$v4 = unserialize($v4v);
die('<pre>'.print_r($v3,true).' '.print_r($v4,true));
outputs (the identical):
Array
(
[lastindex] => 1
[1] => 1
)
Array
(
[lastindex] => 1
[1] => 1
)
so let's now bring them "back to life":
$v3v = serialize($v3);
$v4v = serialize($v4);
die('<pre>'.print_r($v3v,true).PHP_EOL.print_r($v4v,true));
whaaa? how did you remember your integer keys??"
a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}
a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}
and how can i get you to stop???
You can use array_diff instead of strcmp. You can try this -
$v3v = 'a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}';
$v4v = 'a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}';
$v3 = unserialize($v3v);
$v4 = unserialize($v4v);
echo empty(array_diff($v3, $v4)) ? 'Identical' : 'Not Identical';
array_diff($v3, $v4) will return empty array if they are indentical.
Working code

accessing session array data, deleting or changing one of the variables within this array

Here is my session array:
Array ( [username] => dog#dog.net [tmpPayment] => Array ( [mID] => 48 [item_1_amt] => 35.00 [description] => Student ) )
I created the ['tmpPayment'] array with the following code:
$tmpPayArr = array();
$tmpPayArr = array('mID'=>$mID,'item_1_amt'=>'35','description'=>'student');
$_SESSION['tmpPayment'] = $tmpPayArr;
I have looked for a simple answer to three questions: (1)how do I add a variable to the [tmpPayment] array (2)how do I change the value of [amount] variable within the [tmpPayment] array (3)how do I remove/delete the [tmpPayment] array altogether. (4)how do I assign the value of ['tmpPayment']['mID'] to a new variable $memberID. For (3) I have unsuccessfully tried:
unset($_SESSION['tmpPayment']);
I think my main problem is not understanding how to REFERENCE the array and its variables properly.
UPDATE:
I have successfully added and change my SESSION variable with the following:
$_SESSION['tmpPayment']['item_1_amt'] = $x_amount;
$_SESSION['tmpPayment']['description'] = $x_invoice_num;
Is this best practice?
Still need help with (3)...removing the session variable ['tmpPayment'] from the above session array.
Here are the answers. If they aren't working, be sure you're calling session_start(); before you try to modify the $_SESSION array.
$_SESSION['tmpPayment']['new_key_name'] = 'new value';
$_SESSION['tmpPayment']['item_1_amt'] = 12324;
unset($_SESSION['tmpPayment']);
1: $_SESSION["tmpPayment"]["newVariable"] = "value";
2: $_SESSION["tmpPayment"]["amount"] = "$1.78";
3: To do this, you can set ["tmpPayment"] to an empty array like so:
$_SESSION["tmpPayment"] = array();
or set it to null
$_SESSION["tmpPayment"] = null;
I borrowed a bit from this answer: PHP $_SESSION variable will not unset
and as that answer, and the other poster on this question mention, make sure to call session_start(); before doing anything with the session variables.

PHP - Undefined offset (0) even though it holds a value

I'm trying to work in a CodeIgniter environment and while trying to collect and gather some information into variables I'm getting some PHP NOTICE errors that don't seem right.
Here's the chunk of code where the error(s) occur:
if (empty($events['user'][$user_id])) {
unset($events['user'][$user_id]);
} else {
foreach ($events['user'][$user_id] as $event) {
$events['user'][$user_id]['events']['event_id'] = $event_id = $event['event_id'];
$events['user'][$user_id]['event']['date'] = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $events['user'][$user_id]['event']['date'][0]['date'];
$events['user'][$user_id]['event']['request_title'] = $event['request_title'];
$events['user'][$user_id]['event']['event_status_text'][] = $this->events_model->getEventStatusFromSectionStatuses($event_id);
$request_data = $this->requests_model->getRequestInfo($event['request_id']);
$events['user'][$user_id]['event']['ministry'] = $this->ministries_model->getMinistryTitle($request_data[0]['requesting_ministry']);
// more stuff will go here...
}
$content_data['event_status_text'] = $events['user'][$user_id]['event_status_text'];
$content_data['events'] = $events['user'][$user_id]['complete_events'];
$content_data['totals'] = $events['user'][$user_id]['totals'];
$content_data['updated_events'] = $events['user'][$user_id]['updated_events'];
}
The specific line of the first error is the third line inside the foreach loop that ends with ['date'][0]['date']. It's the [0] that PHP is telling me is undefined. However, if I echo that exact same variable like this:
echo $events['user'][$user_id]['event']['date'][0]['date'];
...it outputs a value as would be expected, which also tells me that the [0] is NOT undefined after all. I'm not actually changing the variable. The only difference is that I'm echoing it instead of assigning it to another variable.
If I use # to ignore it in here, it happens again a few lines later on the line ending with getMinistryTitle($request_data[0]['requesting_ministry']).
Can you see what I'm doing wrong? Let me know if you need to see more of the code.
Here's the getEventDates() code as requested (note this is not my code):
function getEventDates($event_id)
{
$sql = "SELECT date FROM `event_dates` WHERE event_id=? ORDER BY date";
$res = $this->db->query($sql, array($event_id));
return $res->result_array();
}
if I print out $this->events_model->getEventDates($event_id) I get the following:
Array
(
[0] => Array
(
[date] => 2014-05-01
)
[1] => Array
(
[date] => 2014-05-08
)
[2] => Array
(
[date] => 2014-05-15
)
[3] => Array
(
[date] => 2014-05-22
)
[4] => Array
(
[date] => 2014-05-29
)
[5] => Array
(
[date] => 2014-06-05
)
[6] => Array
(
[date] => 2014-06-12
)
)
Hmmm... is it possible that this error is happening because there isn't a direct value contained in [0], but rather another array level? Please note that I did not structure this output. Someone else coded this and it's just my job to come in and work with it.
Without seeing the rest of your code this is confusing:
$events['user'][$user_id]['event']['date'] = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $events['user'][$user_id]['event']['date'][0]['date'];
Why would you be setting $events['user'][$user_id]['event']['date'] in one line and then in the next overriding it again?
My best advice would be to set the first assignment in a variable independent of the array, and then calling that variable for the data:
$event_dates_temp = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $event_dates_temp[0];
And perhaps adding a conditional check to ensure you are setting things that exist:
$event_dates_temp = $this->events_model->getEventDates($event_id);
if (array_key_exists(0, $event_dates_temp)) {
$events['user'][$user_id]['event']['date'] = $event_dates_temp[0];
}
Also, it’s unclear at what point you are doing this:
echo $events['user'][$user_id]['event']['date'][0]['date'];
And what is the output when you do dump like this:
echo '<pre>';
print_r($events['user'][$user_id]['event']['date']);
echo '</pre>';
It happens when you are trying to access a value which is not set for that index, please read this link for more information.
There are two options available:
Ignore these notices by telling the PHP error_reporting to not show notices error_reporting(E_ALL ^ E_NOTICE); but it is a good practice to fix this error by adding a check if a value exists.
Fix the values by isset function to see if the value/index contains any data.
If You hide notice set error_reporting(E_ALL ^ E_NOTICE);
Solution is use isset() to solved this issue.

PHP Fatal error: Cannot use string offset as an array

Facing a weird situation with arrays..
I am using LinkedIn API to get profile info which returns data in two formats..
If user has just one educational item
educations=>education=>school-name
educations=>education=>date
...
If more than one education item
educations=>education=>0=>school-name
educations=>education=>0=>date
...
educations=>education=>1=>school-name
educations=>education=>1=>date
...
Now I am trying to make it consistent and convert
educations=>education=>school-name
to
educations=>education=>0=>school-name
But getting error in code that i believe should work
if(empty($educations['education'][0]['school-name']))
{
$temp = array();
$temp['education'][0]=$educations['education'];
$educations = $temp;
}
This fails for "just one educational item", generates error on the first line for (isset,is_array and empty)
PHP Fatal error: Cannot use string offset as an array in ...
print_r returns
[educations] => Array
(
[education] => Array
(
[id] => 109142639
[school-name] => St. Fidelis College
[end-date] => Array
(
[year] => 2009
)
)
)
Usually you'd write the assignment like this:
$temp = array(
"education" => array($educations['education'])
);
To avoid any issues with indexes. This might also fix yours.
If you're unsure about the contents of $educations['education'][0]['school-name'] you can simply check each part:
if(isset($educations['education'], $educations['education'][0], $educations['education'][0]['school-name']))
This works because isset doesn't behave like a normal function. It takes multiple arguments in a lazy manner.
You want:
if(array_key_exists('school-name',$educations['education']))
{
$educations['education'] = array($educations['education']);
}
Today I experienced the same problem in my application. Fatal error: Cannot use string offset as an array in /home/servers/bf4c/bf4c.php on line 2447
line 2447
if (!isset($time_played[$player]["started"])) {
$time_played[$player]["started"] = $time;
}
$time_played was overwritten elsewhere and defined as a string. So make sure you do use unique variable names.
Here's a tip if you're running through a loop, and it breaks:
if( $myArray != "" ){
// Do your code here
echo $myArray['some_id'];
}

unserialize array

I am return a serialize array from a post meta field in wordpress called groups.
here is how it looks in to post meta field.
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
how can i loop trough this and run an if statement i.e.
$mydata = unserialize($meta['groups']);
print_r($mydata);
The unserialzed isnt working for me the ouput i get from the print_r is below
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
which is same as above.
Any help on working with serialized and unserialzed arrays never used before.
Propably magic_quotes is active. Strip the slashes generated by it with stripslashes:
$mydata = unserialize(stripslashes($meta['groups']));
If you want to strip slashes from the whole GPC-Array use this (Credits go to this comment on PHP.net):
if (get_magic_quotes_gpc()) {
$strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
return is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
};
$_GET = array_map($strip_slashes_deep, $_GET);
$_POST = array_map($strip_slashes_deep, $_POST);
$_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
}
print_r(unserialize('a:2:{i:0;s:1:"1";i:1;s:1:"2";}'));
will print
Array
(
[0] => 1
[1] => 2
)
The unserialization works just fine. How do you know if $meta['groups'] contains what you want?
Here is what I obtained using command-line PHP:
php > $x = unserialize('a:2:{i:0;s:1:"1";i:1;s:1:"2";}');
php > print_r($x);
Array
(
[0] => 1
[1] => 2
)
It seems that $meta['groups'] does not contain the serialized string.

Categories