URL variable to Session variable (using GET method) - php

I am trying to store a value obtained from a URL variable into a SESSION variable.
Here is the URL:
Ace Hardware
Here is the SESSION coding, which retrieves the variable, but loses the variable value upon leaving the page.
$_SESSION["store"] = $_GET["store"];
$shopByStore = $_SESSION["store"];
If I plug in the value in quotes as it is below (see "Ace" in code below), it works. But it doesn't work in the code above using the GET method ($_GET["store"])
$_SESSION["store"] = "Ace";
$shopByStore = $_SESSION["store"];

The problem is that you override the $_SESSION["store"] with the $_GET["store"] each time whether the get request exists or not, so it basically only uses $_GET["store"]. You could use this instead:
if (isset($_GET["store"])) {
$_SESSION["store"] = $_GET["store"];
}

At first you need to start the session and then make sure it's already not stored in the session (if it's passed in the $_GET) and if not already saved in the session then store it:
// The first line in your script
session_start();
if (isset($_GET["store"])) {
if (!isset($_SESSION["store"])) {
$_SESSION["store"] = $_GET["store"];
}
}
Read more on PHP manual.

Related

How to unserialize codeigniter session data from database

I wan to use CI session in a external script and I got following data from database.
__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;
I have tried unserialize and unserialize(base64_decode($data)) but I am fail yet.
Please help to extract this data.
I got the solution here
So I have used session decode
session_decode('__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;');
So session decode stored all the encrypted data in normal php session.
Which I can access using: echo $_SESSION['ci_UserID'];
Well guys thanks for the help
If this is a session variable, you can use CodeIgniter's own session library. Consider the following code (in a controller):
$this->load->library('session'); // load the session library
$session_data = $this->session->all_userdata(); // get all session data
print_r($session_data); // print and get the corrresponding variable name, e.g. "item"
$var = $this->session->userdata('item'); // pick one that suits your needs, e.g. item
Sorry, I have read "the external script" only after having posted the code. This obviously only works in the CI framework.
For an external script you may need to have a closer look. The variables are separated by ";" and "|" and then serialized, so this might work (not tested):
$row = explode(';', '__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;'); // load the database row
$userid = explode('|', $row[1]);
$userid = unserialize($userid[1]); // now $userid holds the value "2"

how to add an array to a session php

I want to add different stuffs to costumers cart but before adding the stuff transition in the database costumer must pay and then redirect to another page after Successful transition i need the chosen stuffs id's i tried using $_POST but the browser does not send the post value because of payment system in the middle i tried using sessions instead
I want to add array of integers to a session control i already tried using this code
$t=array(1,2,3,4,5);
$_SESSION['exam_id']=$t
I don't know if i can do such a thing or not but what is the parallels
What you specified is working correctly. Sessions can hold arrays.
The session superglobal is an represented as an array itself within PHP, so you can just get and set values by doing the following
Setting:
$_SESSION['exam_id'][] = "new value";
or
$_SESSION['exam_id'] = array("new value", "another value");
Getting:
$_SESSION['exam_id'][0]; // returns a value
This returns the first value in the exam_id array within the session variable
You will need to start the session. Make your code;
<?php
session_start();
$t = array(1,2,3,4,5);
$_SESSION['exam_id'] = $t;
You need session_start()
You didn't have a semi-colon ; at the end.
you can use array in session like this..
you have to start session with session_start();
and then store your array to session $_SESSION['items'][] = $item;
and then you use it, whenever you want:
foreach($_SESSION['items'][] as $item)
{
echo $item;
}
You can set PHP sessions equal to an array just like you're doing.
To set the $_SESSION variable equal to all POST data, you can do this:
$_SESSION['exam_id'] = $_POST;
Be sure to add session_start() prior to declaring any session variables.
$t=array(1,2,3,4,5);
$_SESSION['exam_id'] = array();
array_push($_SESSION['exam_id'],$t[0]);
array_push($_SESSION['exam_id'],$t[1]);
array_push($_SESSION['exam_id'],$t[2]);
array_push($_SESSION['exam_id'],$t[3]);
array_push($_SESSION['exam_id'],$t[4]);

php session variable is null

i am creating session variables to store data in an array of object. this array is assigned to sessions. I am later sending a get call to different page with an id and want to access the corresponding data from the sessions. however i am getting the data as null. here is my code
page 1:
session_start();
for ($i=0;$i<100;$i++){
$object[$i]->name = $ret_obj[$i]['name'];
$object[$i]->birthday_date = $ret_obj[$i]['birthday_date'];
$_SESSION[$i] = $object[$i];
}
var_dump of session prints the session variable correctly.
Now in the for loop i am making a call to page 2:
page2.php?pid=$i
page 2:
session_start();
$pid = $_GET['pid'];
print_r($_SESSION[$pid]);
print_r($_SESSION);
I am getting value in $_SESSION but not in $_SESSION[$pid]
You should take a look at the following post: Notice: Unknown: Skipping numeric key 1 in Unknown on line 0. To clarify, try adding a character prefix instead of just using numbers.
If your code supplied here is all of it, then you are saying:
$p13nid = $_GET['pid'];
Rather than:
$pid = $_GET['pid'];
Which would make it work for you.

PHP $_SESSION variables not storing values

I'm trying to use PHP session variables to carry data over multiple pages. I am using session variables on many parts of my site, but this is the first place where they don't work.
I'm setting it like this:
$_SESSION["savedRetailerName"] = $foo;
And calling it like this:
echo $_SESSION["savedRetailerName"];
The session id remains the same between these two pages, and I'm sure that I'm setting the variables right and that they are being called right. I start the session correctly, and even on that particular page, other session variables are being shown properly.
How can I begin to debug this odd behavior?
Edit:
There are two different pages I'm currently dealing with. Page 2 sets the session variables, and there is a button that will return the user to Page 1. The idea is to still have the fields in Page 1 filled in if the user wishes to return to Page 1.
It is not a cache problem, and I can return other session variables in the exact same spot in my code as where I am failing to return these variables.
The only other code that may be pertinent is the back button handler (jQuery):
$('#backButton').live('click',function() {
window.location.replace("page 1");
});
Edit 2:
I believe this isn't working because of something with variables here:
<?php
$retailerName = $_REQUEST["retailerName"];
$description = $_REQUEST["description"];
$savingsDetails = $_REQUEST["savingsDetails"];
$terms = $_REQUEST["terms"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$zone = $_REQUEST["zone"];
$dateExp = $_REQUEST["dateExp"];
$tag = $_REQUEST["tag"];
$_SESSION["rn"] = $retailerName;
$_SESSION["de"] = $description;
$_SESSION["sd"] = $savingsDetails;
$_SESSION["tm"] = $terms;
$_SESSION["ph"] = $phone;
$_SESSION["ad"] = $address;
$_SESSION["zo"] = $zone;
$_SESSION["ex"] = $dateExp;
$_SESSION["tg"] = $tag;
?>
I am able to set any session variable to a string, but it won't set to a variable.
You want to use session_start before you set or use any session variables. You only need to call it once.
If it's working in other places, odds are that this particular block of code is being executed before session_start is called.
remove all non printable characters before <?php
you may not see them..
You have spaces before your <php tag
You don't have session_start() anywhere
You are using the $_REQUEST variable which is sketchy (use $_GET or $_POST instead)
You would also need to register the session using
session_register # php.net

How to tell if a session is active? [duplicate]

This question already has answers here:
Check if PHP session has already started
(27 answers)
Closed 1 year ago.
Per request, there are a few different ways that you can tell whether or not a session has been started, such as:
$isSessionActive = (session_id() != "");
Or:
$isSessionActive = defined('SID');
However, these both fail if you start a session, then close it; session_id() will return the prior session's ID, while SID will be defined. Likewise, calling session_start() at this point will generate an E_NOTICE if you already have a session active. Is there a sane way to check if a session is currently active, without having to resort to output buffering, the shut-up operator (#session_start()), or something else equally as hacky?
EDIT: I wrote a patch to try to get this functionality included in PHP: http://bugs.php.net/bug.php?id=52982
EDIT 8/29/2011: New function added to PHP 5.4 to fix this: "Expose session status via new function, session_status"
// as of 8/29/2011
$isSessionActive = (session_status() == PHP_SESSION_ACTIVE);
EDIT 12/5/11: session_status() on the PHP manual.
See edits to the original question; basically, PHP 5.4 and above now has a function called session_status() to solve this problem!
"Expose session status via new function, session_status" (SVN Revision 315745)
If you need this functionality in a pre-PHP 5.4 version, see hakre's answer.
I worked around this by adding a couple wrapper functions around the various session creation/closing/destroying functions. Basically:
function open_session() {
session_start();
$_SESSION['is_open'] = TRUE;
}
function close_session() {
session_write_close();
$_SESSION['is_open'] = FALSE;
}
function destroy_session() {
session_destroy();
$_SESSION['is_open'] = FALSE;
}
function session_is_open() {
return($_SESSION['is_open']);
}
Hackish, but accomplished what I needed.
I'm running into this as well, and a setting in $_SESSION is not an option for me. For PHP 5.3.8:
If any session has been started with the request, define('SID') will return FALSE, as well as $_SESSION is unset.
This is independent whether or not session_id() has been used to set a session id or not.
After the first session_start(), SID is defined and $_SESSION is set to an empty array.
session_destroy() does unset the session_id(), it's an empty string then. SID will remain defined (and set to it's previous value which might be an empty string). $_SESSION is left unchanged. It will get reset/populated next time session_start is called.
With these states, especially as session_id() can be called in between to set the id for the next session, it's not possible to safely determine the session status with SID, $_SESSION and session_id().
"Trying" with session_start() (e.g. with #) might not be really helpful, as this will change the session status and changing the contents of $_SESSION (and adding a set-cookie header if the cookie was not part of the request). It was not fitting in my case.
While I was running tests, I came across the behaviour, that you can not try to change the ini setting of session.serialize_handler when the session is active, not even when you set it to the same value. Same is true for session.use_trans_sidDocs which is more lightweight. This lead me to the following function:
/**
* #return bool
*/
function session_is_active()
{
$setting = 'session.use_trans_sid';
$current = ini_get($setting);
if (FALSE === $current)
{
throw new UnexpectedValueException(sprintf('Setting %s does not exists.', $setting));
}
$result = #ini_set($setting, $current);
return $result !== $current;
}
As far as I can see, the error is checking for active session status only (not disabled), so this should not return a false positive when sessions are disabled.
To get this function compatible with PHP 5.2, it needs a little modification:
/**
* #return bool
*/
function session_is_active()
{
$setting = 'session.use_trans_sid';
$current = ini_get($setting);
if (FALSE === $current)
{
throw new UnexpectedValueException(sprintf('Setting %s does not exists.', $setting));
}
$testate = "mix$current$current";
$old = #ini_set($setting, $testate);
$peek = #ini_set($setting, $current);
$result = $peek === $current || $peek === FALSE;
return $result;
}
Some sandbox.
The following code only dumps one session_id() for me, not two
session_start();
echo session_id();
session_destroy();
echo session_id();
If you're having difficulties with this still you can try creating a variable to check, that you destroy when you destroy the session.
session_start();
$_SESSION['intialized'] = 'This will not print';
$_SESSION = array(); // Unset all variables
session_destroy();
echo $_SESSION['initialized']; // No output
Here's a good drop in replacement that won't break stuff when you move to 5.4:
if(!function_exists('session_status')){
function session_active(){
return defined('SID');
}
}else{
function session_active(){
return (session_status() == PHP_SESSION_ACTIVE);
}
}
Ken, if the session is destroyed, the $_SESSION array should not be available...or at the very least, your values should be unset. So, in theory (untested) you should be able to check the array for a value to know if anything is currently set.
There are multiple places you need to check to verify the session is active:
1- cookie exists and is not expired
2- underlying session storage mechanism (file system or database) has a record matching the cookie.

Categories