how to add an array to a session php - 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]);

Related

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.

How can I set a session for multiple links that I want to disable?

piece of file1.php:
Add this to DB
This takes the user to a page where the data gets inserted into the database.
file2.php :
$clicked = $_GET['addid'];
$_SESSION['clicked'] = $clicked;
// data gets inserted
header("Location: file1.php?id=$clicked");
But I have got multiple pages (like: file1.php?id=1 | file1.php?id=2 | file1.php?id=3 etc.).
Can the session variable handle multiple numbers? Is there any way to do this?
Any help appreciated.
(P.S.: Currently I am using the GET method to disable the links, but I think SESSION is more reliable.)
(P.P.S.: I need this for a voting script.)
To hold more data in one session variable, you need to create a multi-dimensional array which will hold multiple against $_SESSION['checked']. You can do this like:
$clicked = (int)$_GET['addid'];
$_SESSION['clicked'][$clicked] = true;
// data gets inserted
header("Location: file1.php?id=$clicked");
(also, you should be sanitizing $_GET['addid'].
Then to check if it is set, you can use array_key_exists:
if(array_key_exists($clicked,$_SESSION['clicked'])){
echo "this button should be disabled!";
}
I am not sure I understood right your question, but if it is how to send an array of data with the same id via an http request you can use this syntax for the url
file.php?arr[]=val1&arr[]=val2&arr[]=val3
from your php code you would access the values as a regular array
Can the session variable handle multiple numbers? Is there any way to do this?
The session variable can store an array
$_SESSION['clicked'] this session variable can store one value at a time.
If you want use 2 dimension array to handle multiple values.
$clicked = $_GET['addid'];
Ex: $_SESSION['clicked'][$clicked];
firstly concatinate all the ids with comma in a string as $var = 1,2,3,4 and then pass it using GET.
Then there on that page you can explode it from comma and can store it in array and then foreach loop for the array will do it for you. Hope it works.

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 push values into an array along with incrementing the array index while inserting?

I have a an array I want, whenenever i submit my form the post value get inserted into that array, every time with new incremented index..
How can I do that? And yes submited page is redirected to itself...
In PHP:
$arr[] = value;
$arr[] = other value;
In HTML:
<input type="text" name="arr[]" />
<input type="text" name="arr[]" />
You could solve this using the session-variables. This way the data won't be overridden. Here's an example:
$_SESSION['formdata'][] = $_POST['value1'];
$_SESSION['formdata'][] = $_POST['value2'];
After you reload the script the data will still be available an pushing other values into the array won't override the old ones. You just do it again:
$_SESSION['formdata'][] = $_POST['value3'];
$_SESSION['formdata'][] = $_POST['value4'];
Calling the $_SESSION['formdata']-Array you now have all 4 values stored in there.
** EDIT **
I am finally home, and as promised I'm offering another solution using cookies, since sessions don't work for you, as we've already discussed. So here we go...
First of all we need to think of the way we want to name the cookie. I would suggest we would do this by ip-address and any suffix, to ensure, that it is really the user who has already filled, the former forms.
So we could go like this:
$dataArray[] = $_POST['value1'];
$dataArray[] = $_POST['value2'];
Then we need to store the data into an cookie. We do this by serializing the array, since we don't want to save hundreds of cookies. This would work like this:
$cookievalue = serialize($dataArray);
// Here we actually generate a cookiename in the format of "IP_formdata"
setcookie($_SERVER['REMOTE_ADDR'] . '_formdata', $cookievalue);
So far so good. Within the next form we retrieve the cookie-data and unserialize the data, so we can extend this array:
$dataArray = unserialize($_COOKIE[$_SERVER['REMOTE_ADDR'] . '_formdata');
Now we can add other values to the array from the second form:
$dataArray[] = $_POST['value3'];
$dataArray[] = $_POST['value4'];
After all additional values have been put into this array we serialize it again and store it into the again again:
$cookievalue = serialize($dataArray);
setcookie($_SERVER['REMOTE_ADDR'] . '_formdata', $cookievalue);
Now we can repeat this steps for all further forms. Just remember that if you want to work with the data you first have to unserialize the data and store it into an array.
And don't forget as I have already stated in the comments: The user can turn off cookies, then the whole thing won't work. You could also add some additional checks to verify that this is the correct user or something. I haven't tested the code, but I think it should work in a way like this and I hope I could help you or at least give you a hint :)

how do i reset the value of a single session array index in codeigniter?

Using a user model which returns an array that looks like this:
$user_data['display_name'] = "John Doe";
$user_data['avatar'] = ./images/user144.jpg";
i create my session using $this->session->set_userdata('user_data',$user_data);
now if on another controller i let the user change his avatar,
how can i replace the session variable associated to that?
like $this->session->set_userdata('user_data["avatar"]',$new_avatar);
just wont work right?
hee thanks for the help...
From looking at an overview of your code, I'm guessing the best way to go about this is to unset the data and reset it.
Use $this->session->unset_userdata('thesessiontounset');
Then set it back up with the new information and old.
The session->set_userdata() function will only let you modify one key at a time. In your case the key refers to an array so what you're trying to do isn't possible in the way you're attempting to do it.
When I'm updating my session I run something like this.
//Create or setup the array of the fields you want to update.
$newFields = array('avatar' = > 'image01.png');
//Check to see if the session is currently populated.
if (!is_array($this->session->userdata('abc'))){
//...and if it's not - set it to a blank array
$this->session->set_userdata('abc',array());
}
//Retrieve the existing session data
$existing_session = $this->session->userdata('abc');
//Merge the existing data with the new data
$combined_data = array_merge($this->session->userdata('abc'), $newFields);
//update the session
$this->session->set_userdata('abc',$combined_data);
More details on array_merge can be found here
First controller
$user_data['display_name'] = "John Doe";
$user_data['avatar'] = "./images/user144.jpg";
$this->session->set_userdata('user_data',$user_data);
Second controller
$user_data = $this->session->userdata('user_data');
$user_data['avatar'] = $new_avatar;
$this->session->set_userdata('user_data', $new_avatar);
It is a bit late, but it might be useful to someone else, this seems to work:
$this->session->userdata['user_data']['avatar'] = $new_avatar;
$this->session->userdata['other_data']['other'] = $other;
$this->session->sess_write();
This allows you to edit values in array just like you do with $_SESION['user_data']['avatar'] = $avatar, with 'only' one extra line and only using CI library.
For Unset Session variable
$this->session->unset_userdata('avatar');
For Set Session variable
$this->session->set_userdata('avatar', '/images/user144.jpg"');
Use just like this
$this->session->set_userdata('session_var',"");

Categories