hi i know how to store post value into session but how can i store session value into post.
post into session
$_SESSION['name'] = $_POST['name'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['mno'] = $_POST['mno'];
$_SESSION['age'] = $_POST['age'];
I have an array stored in session and i want to store it into post.
Can i do this? If yes then how?
I want to store all array value in post from session
The opposite should work without any problems.
$_POST['name'] = $_SESSION['name'];
$_POST['email'] = $_SESSION['email'];
$_POST['mno'] = $_SESSION['mno'];
$_POST['age'] = $_SESSION['age'];
If you want to hold an array you can do it like this:
$datapost = array ( 'name' => $_SESSION['name'], 'email' => $_SESSION['email']);
$_POST['info'] = $datapost;
$_POST is not a persistent store where you can put things. The point of $_POST is that it is populated at the start of the request, with the data that was passed to the server from the client (usually, web browser).
You can write into that array, but it won't have any special effect. It's just an array variable that's globally available in all scopes of your code. Normally, you'd just want to create a new array, and assign whatever you want in there:
$data = [];
$data['stored_foo'] = $_SESSION['foo'];
$data['submitted_foo'] = $_POST['foo'];
See also Why are Global Variables Evil?
If you want to send data back to the browser, you can:
put it in the output (using echo etc)
put it in an HTTP header (using the header() function)
put it in a cookie (which will be sent as an HTTP header, crafted for you by the setcookie() function)
Related
I have this code.
$message = "";
if($_REQUEST['msg'] == "new"){
$message = "New User has been added successfully";
}else if($_REQUEST['msg'] == 'edit'){
$message = "User has been saved successfully";
}else if($_REQUEST['msg'] == 'update'){
$message = "User(s) has been Updated successfully";
}
can any one please tell me here what is ['msg'] and please explain the functioning of $_REQUEST?
$_REQUEST is a super global array. Just like $_GET, $_POST, $_COOKIE, $_SESSION etc. That means it can store a list information numerically or associatively.
For example:
Associative:
$array = array(key->value, key->value);
Numeric:
$array = array([0]->value, [1]->value);
In the case of $_REQUEST or $_POST or $_GET these arrays will store encoded data sent to the PHP header.
for example:
$_REQUEST['key'] = value;
or
you have a navigation item:
<a href='?key=value'>value</a> //for $_GET
PHP will encode that key->value into the url and save it to the super global array that you are using. To access it call:
echo $_REQUEST['key']; //returns 'value'
In your case msg is, so far, not encoded to the browser. It needs to be passed by different means(forms, href's etc.). So,
$_REQUEST['msg'] = 'new';
if(isset($_REQUEST['msg'])){ //use isset() to avoid an error
if($_REQUEST['msg'] == "new"){
$message = "New User has been added successfully";
}else if($_REQUEST['msg'] == 'edit'){
$message = "User has been saved successfully";
}else if($_REQUEST['msg'] == 'update'){
$message = "User(s) has been Updated successfully";
}
} //returns $message = "New user..."
$_REQUEST is not suggested because it makes it hard to control what information is processed. $_GET requests show the key->value pairs in the url. Information that you don't want as visible probably shouldn't be shown there. With $_REQUEST a user can send that key->value pair over the url to see what information needs to be passed and exploit that in other ways (google cross-site request forgeries).
TL;DR : $_REQUEST['msg'] -- 'msg' is a key in a key->value pair ('new'| 'edit' | 'update' being the value)
$_REQUEST is a superglobal array that saves values that can be used by the user in any scope in other parts of the website.
$_REQUEST contains values passed by post,get and/or cookies. As get is easy to hack so safer mechanism would be to use post when send data from one html/php file to another. Then you need to use $_POST to get the data. More detail you can find from this link.
So in your case previous html page has used either of the techniques to use a variable/parameter/cookie named msg to pass data.
The $_REQUEST['msg'] is a key from the superglobal array.
Basically $_REQUEST will access it even if the variable was sent through $_POST or $_GET :
$_POST :
$_GET : page.php?msg=testMsg
I've never run into this before but for some reason, when I am using AJAX to set a session variable, the session will not hold them.
Here is what I have:
session_start();
if(isset($_POST['selected'])){
$_SESSION['user']['theme'] = array ('selected' => true);
} // This should be now set with the value and it is for a time, but unsets
if(isset($_POST['theme'])){
$_SESSION['user']['theme'] = array('name' => $_POST['theme']);
} // So should this
What I am seeing when I do a print_r under both if constructs is only the $_SESSION['user']['theme']['name'] var and the other is not set. If I do a print_r just under the selected var, I can see it just fine. Somewhere, the key and value are disappearing for selected.
Why is this happening? I'm expecting to see both name and selected.
Like i said in my comment, you're overriding the array :)
session_start();
//changed it to unset if not in $_POST
$_SESSION['user']['theme']['selected'] = isset($_POST['selected']);
if(isset($_POST['theme'])){
$_SESSION['user']['theme']['name'] = $_POST['theme'];
} // and unset it too
else {
$_SESSION['user']['theme']['name']= "";
}
You need to start the session first
session_start();
if(isset($_POST['selected'])){
$_SESSION['user']['theme'] = array ('selected' => true);
}
And also check whether the $_POST values are not empty.And you need to unset the name in session then assign it like
if(isset($_POST['theme'])){
unset($_SESSION['user']['theme']['name']);
$_SESSION['user']['theme'] = array('name' => $_POST['theme']);
}
At the start of any page that sessions variables are accessed in any way, the first command must be a call to session_start();
I have a session for login data, and I am trying to take it and put it into a variable to shorten whenever I want to echo or use the ID, Username, or Email. What is happening is that now I have it in a variable, but when I echo it, it shows it in an array.
Here is my variable data.
$User = htmlentities(ucwords($_SESSION['user']['username']));
$Email = htmlentities($_SESSION['user']['email'], ENT_QUOTES, 'UTF-8');
If I echo any of these, it returns "Array".
EDIT
I fixed my solution by changing how I get my $_SESSION data, and using unset to get rid of the array. Now I can just do this,
$User = $_SESSION['user']["username"];
$Email = $_SESSION['user']["email"];
Thank you for reminding me about how I'm even getting my session data in the first place =]
If you are using classes, where you specify all your variables, maybe try this:
$User = $_SESSION['user']->username;
echo $User;
where user is your class and username is your variable
WHen you add it to your session, you need to do soething like this:
$_SESSION['user'] = new user();
$_SESSION['user']->username= 'whatever value it is';
I have two $_SESSION variables declared as array in index.php, say:
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
I make a AJAX call from index.php to result.php, where values of session variables are changed
to, say:
$_SESSION['a'] = array(2,3,1,4);
$_SESSION['b'] = array(5,6);
What I do is, I remove the first element from both the arrays and append it back to first array, $_SESSION['a'].
On successful AJAX call, I want to print the first elements of both the variables in index.php. Is it possible?
Yes, on a successful ajax call, you can do that.
This is pretty straight forward.
In your results.php you simply returned the new data with a bit of JSON.
result.php:
//set the session vars to whatever here....
//now, return them. In the example, I shall assign your session vars to temp vars.
$sessA=$_SESSION['a'];
$sessb=$_SESSION['b'];
echo json_encode(array('a'=>$sessA,'b'=>$sessb));
And now in your AJAX (assuming you're using jQuery):
$.getJSON('results.php', function(data){
alert(data.a);
alert(data.b);
});
And there you have it.
EDIT:
In your index.php, you say you set the session vars to the original value. But in your comments, you say you want to use the new vars in index.php. This won't be possible if you are setting them to the original value in index.php on every request. What you should do is check if they're already set first, and then do what needs to be done. Like this:
instead of:
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
Do this:
if ( isset($_SESSION['a']) === false && isset($_SESSION['b']) === false )
{
# - The vars are not already set...so it's okay to set them to its original value.
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
}
I am looking for a way to delete only certain amounts of SESSION data that is stored whilst preserving the session data associated with the user being logged on.
At the moment I am doing this by individual unset statements to the SESSION variables I want to delete.
However I was hoping there may be a more clever way to just delete a whole section of the SESSION array whilst preserving specific variables
e.g.
$_SESSION['username'];
$_SESSION['user_id'];
$_SESSION['ttl'];
The use case for this process would be:
User Logs In --> User performs task --> Once task is complete delete session data associated with task --> User is still logged in!
I had considered perhaps using a table in my Database monitoring logins, what are your opinions on that?
Thanks for your time!
There is no way to delete "whole section of the SESSION array whilst preserving specific variables".Instead of that you can use two dimensional array for a task and delete that array.
$_SESSION["task1"]["username"] = "name"
$_SESSION["task1"]["pass"] = "pass"
$_SESSION["task2"]["name"] = "name";
when task1 complete delete like
unset($_SESSION["task1"]);
now $_SESSION["task2"] still exist.
Well you could store all this volatile data inside another key:
$_SESSION['volatile'] = array(
'one' => 'value'
);
If you dnt want to do that you could use array comparison functions like:
// specify what keys to keep
$_SESSION = array_intersect_key($_SESSION, array('keepme1', 'keepme2', 'etc'));
//specify what keys to remove
$_SESSION = array_diff_key($_SESSION, array('deleteme1', 'deleteme2', 'etc'));
As far as the DB you could do that but its not necessary to accomplish your objective, and unless there are moving parts you didnt list in your original question id say you probably dont need to do anything that complex right now.
Structure your session data in a hierarchy:
$_SESSION['loggedIn'] = TRUE;
// Temporary session data
$_SESSION['temporary'] = array(
'temp_var1' => 'foo',
'temp_var2' => 'bar',
// ...
'temp_var99' => 'baz'
);
echo $_SESSION['temporary']['temp_var2']; // bar
// Remove all temporary session data
unset($_SESSION['temporary']);
echo $_SESSION['loggedIn'] ? 'yes' : 'no'; // yes
I will have to disagree with #sathishkumar, the following method destroys partially session variables.
public static function destroyPartial($keys)
{
if (session_status() === \PHP_SESSION_NONE) {
session_start();
}
if (!is_array($keys)) {
$keys = [$keys];
}
foreach ($_SESSION as $k => $v) {
if (in_array($k, $keys, true)) {
unset($_SESSION[$k]);
}
}
$recoveringSession = $_SESSION;
session_destroy();
session_start();
$_SESSION = $recoveringSession;
}
In the php docs for the session_destroy function, we can read this:
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.
So, the "trick" is to call session_start AFTER session_destroy.
Hope this helps.