Adding to an array in $_SESSION - php

I have a survey script that has 3 questions per page. When users answer the questions on the first page and click next, the data from the previous page is stored in $_SESSION['survey']['data'] by doing this:
$data = postToArray($_POST, $ignore_fields);
$_SESSION['survey']['data'] = $data;
$data is an array that looks like:
array('question' => 'answer', 'question' => 'answer');
postToArray does a few checks and manipulates the actual submission a bit, before returning it to $data.
When the user is on page two of the survey, the same thing happens over. I assumed that when $data gets added to the session, via $_SESSION['survey']['data'] = $data;, that it would append to the session array if the 'question' (key) did not exist, but if it did (because the user went to a previous page and changed their answer), that the existing value with the same key would be overwritten, however the last page's submission overwrites everything in the ['data'] array in the session. Come to think about it, that makes perfectly sense.
I tried various things, such as retrieving the $_SESSION['survey']['data'], storing it in array, reading the last submission, merging the arrays, and then re-saving everything in the SESSION, but my code didn't work out -- does this approach make sense? Is that possible?
I also tried array_push, but no luck there.
In addition, I tried adding to $_SESSION['survey']['data'][], which at least saves everything (each submission in its own array), but then if the user goes back a page, any values they change and re-submit are added as another array.
Preferably, I'd like one giant array with all questions/answers and it keeps adding to that array and overwrites any values with existing keys.
What's the best approach?
Thanks,
-Ryan
SOLUTION IMPLEMENTED
$data = postToArray($_POST, $ignore_fields);
foreach($data as $question => $answer)
{
$_SESSION['survey']['data'][$question] = $answer;
}

Try to serialize the data before saving it in a session variable.
http://php.net/manual/en/function.serialize.php

Loop through the $data array and set it up as naiquevin stated, $_SESSION['survey']['data'][$data['question']] = $data['answer'].

<?php
session_start();
if(!isset($_POST["submit"])){
$_SESSION["abc"]=array("C", "C++","JAVA","C#","PHP");
}
if(isset($_POST["submit"])){
$aa=$_POST['text1'];
array_push( $_SESSION["abc"],$aa);
echo "hello";
foreach( $_SESSION["abc"] as $key=>$val)
{
echo $val;
}
}
?>

Related

Passing a multi-dimensional array using sessions in PHP

I am currently trying to pass a multidimensional array through sessions while also being able to dynamically add/remove from it (it is a wish-list). The index of the array will be the ID of an item I am adding to the array. I've tried serialization, using variables instead of the actual session and none of it worked properly for me.
My issue is that my array will not pass from page 1 to page 2. Page 1 is what happens when the user clicks any "add to wish-list" button
I searched up on Google and wrote something similar to this:
page 1:
session_start();
$_SESSION['wishlist'] = array();
$id = $_GET['id'];
$imageFileName = $_GET['ImageFileName'];
$title = urldecode($_GET['PictureName']);
$_SESSION['wishlist'][$id]=array("id"=>$id,"title"=>$title,"imageFileName"=>$imageFileName); // Here im making the multidimensional array
$_SESSION['wishlist'] = $_POST; //found this way on Stackoverflow
header('Location:view-wish-list.php'); //move to second page
page 2: trying to start session and print out the array to test:
session_start();
var_dump($_SESSION['wishlist']);
Var Dump gives me array(0) { }
Any help would be appreciated. Thank you.
You have to commit (write) the session before redirection or the second request may occur before the session data is available on the server:
session_write_close();
header('Location:view-wish-list.php'); //move to second page

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]);

Form submission: PHP S_SESSION statements within a foreach loop

Let's suppose I have the following PHP code which attempts to read from an array called $arr which takes on the values {fullname, studentnumber, email}. Upon submission of my HTML form, this PHP code will execute the foreach loop, and store the values posted to the page in the $_SESSION array.
foreach($arr as $field):
$_SESSION[$field] = $_POST[$field];
endforeach;
The above code doesn't work as intended. If I were to replace the above code block with the code below, the values in the fields on my page get stored correctly in the $_SESSION array.
$_SESSION[fullname] = $_POST[fullname];
$_SESSION[studentnumber] = $_POST[studentnumber];
$_SESSION[email] = $_POST[email];
How do I accomplish this, in an efficient and expandable way? I don't want to have to write new $_SESSION statements every time I add a new field to my form.
EDIT: // The first block of code actually works as intended. There was a typo originally!
what you want is to use array_keys() otherwise you're getting the array contents.
foreach (array_keys($arr) as $field)
Let me know if this works/is what you're looking for :)

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.

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 :)

Categories