Store all post variables/values in a session
This is one of those things I use all the time but because I can’t remember things like this, I always have to look for the exact code to do it…
This will take all the values submitted in a form and store them in a session:
foreach($_POST as $k=>$v) {
$_SESSION[$k]=$v;
}
And when you’re ready to dump the session values…
session_unset();// reset session array
session_destroy(); // destroy session.
February 8th, 2007 at 12:39 pm
oh my goodness, I didn’t even know it was possible to just loop through the variables like that! Thanks for sharing… you just made my life about 1 million times easier
February 27th, 2007 at 2:22 pm
try var_dump($_SESSION);
February 28th, 2007 at 1:51 pm
If you would like to retrieve a previous post later in your web app, you can store the current post as follows:
$_SESSION['previous_post'] = $_POST;
Then when your ready to use the old post you can either completely overwrite the current post as follows:
$_POST = $_SESSION['previous_post'];
or access that info directly from the session (may have side effects) as follows:
echo $_SESSION['previous_post']['some_posted_variable'];
March 1st, 2007 at 4:38 pm
var_dump($_SESSION) will NOT destroy the values or session… it will just display the values to the screen.
see function var_dump on the php manual
May 28th, 2007 at 9:03 pm
[...] To create the session cookies - very easy:<?php foreach($_POST as $k=>$v) { $_SESSION['post'][$k]=$v; } ?> (I’ve actually mentioned this method before) [...]
June 29th, 2007 at 6:50 am
foreach($_POST as $k=>$v) {
$_SESSION[$k]=$v;
}
That can also be a security risk, depending on how you wrote the rest of the app… such as if you store something like a userID as a sess, and someone posts in a fake form with userID=125, that will now set the sess variable and have them running around as user 125 from now on, with access to that account, or any other account they want to post in as. If you do store key info in a sess that people could potentially guess (or bots post thousands of forms trying to hit something) you won’t want to use that technique.
April 28th, 2008 at 12:17 am
Can someone please tell me how can I post the $_SESSION variables so that I can use them in a mail( action. Sorry for my english !
April 28th, 2008 at 8:19 am
Not sure exactly what you mean but two things:
1) if you’re processing a form that SESSION info - you don’t need to have it in POST to be able to access it. As long as the page that’s processing the form has session_start() - you have acces to that SESSION info and you can then put it in the mail() as needed.
2) if you need to have it in the POST for some reason (maybe you’re processing the form on ANOTHER server - or another service is processing the form) - then when you’re creating the form you can put the SESSION info into hidden input fields in the form and it will be sent along in the POST with the rest of the form…
Hope that makes sense.