Storing all POST data in SESSION - php

I have more values (over 20) from $_POST like this...
$name = $_POST['name'];
$username = $_POST['username'];
$city = $_POST['city'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
NOTE : I have prevented there values from SQL injection.
My question is can I know is there a way to store all these POST values in SESSION at once?
Instead of this method..
$_SESSION['name'] = $name; etc
any answers will be highly appreciated.
Thank you.

$_SESSION['post-data'] = $_POST;
That will create an array of the post values in a single session variable. The values would be accessible as
$_SESSION['post-data']['name']
$_SESSION['post-data']['username']
...

You can add one array to another.
$_POST and $_SESSION are just arrays.
Note that the keys in the second array take priority in case of duplicates.
$_SESSION += $_POST;
However, I don't see this ending well, since the client side can inject anything he wants to the session, E.G. hijacking your users session id.

If you looking for session variables that are set using the same key as the posted array, you could use this:
foreach ($_POST as $key => $value) {
${$key} = $value;
$_SESSION[$key] = $value;
}
This will make your $_POST array into variables based on the array key and also set the session at the same time. You could then access your name post by using either $_SESSION['name'] or $name.
This means you will not need to use: $name = $_POST['name']; anymore. As the above code will set the name variable for you and also set the session variable.

The best explanation of passing variables either with form post or header location redirection inside php check out my answer in this thread: How to pass variables received in GET string through a php header redirect?

Related

How to combine the $_SESSION into one variable in PHP mysqli ?

normally, i use the single $_SESSION for single field in the table as below in mysqli, let's say i use 'email' field in users table
$email = mysqli_real_escape_string($connect,$_POST["email"]);
$_SESSION['email'] =$email;
but it only can use email as sessions right ?
But what if i have multiple fields in the users table such as username, password, gender ?. How to combine/bind all the $_SESSION fields together into one variable ?
$user = $sessions_variable['username'];
thanks in advance :)
$_SESSON is an array. So your first move is to read up on arrays in the PHP manual.
After that you'll be able to either assign different values to different $_SESSON elements
$_SESSION['email'] = $email;
$_SESSION['username'] = $username;
or, after getting the user info from a database, assign it to a single element
$_SESSION['user'] = $row;
You can create multidimensional array in session like this
$_SESSION['user']['username'] =$username;
$_SESSION['user']['email'] =$email;
then you can pass whole user session array to single variable.
$user = $_SESSION['user'];
We can create multidimensional array for session follow the below procedure.
Example:
$_SESSION['foo']['foo_1'] =$foo1;
$_SESSION['foo']['foo_2'] =$foo2;
$_SESSION['foo']['foo_3'] =$foo3;
...
Now if we want to use whole foo array in single variable. you have to pass it like this.
$foo_whole_session = $_SESSION['foo'];
You can check what you found using print_r($_SESSION).

PHP: How to store dynamic variables within session variable?

Here is what I'm trying to do:
$username = 'john';
$_SESSION['data'] = "Hello ".$username;
$username = 'mike';
$new = $_SESSION['data']; // trying make it like: $new = "Hello ".$username;
echo $new // should output: "Hello Mike"
I'm trying to save a phrase with a dynamic variable into a $_SESSION variable, so the phrase can later be change on a different page depending on the dynamic variable.
Is this possible, and how can it be done?
You could use string formatting for that. Take a look:
$username = 'John'; // not really needed for this test
$_SESSION['data'] = "Hello %s";
$username = 'Mike';
$text = sprintf($_SESSION['data'], $username);
echo $text
Output:
Hello mike
See the code in action here.
It will not work the way you have it written, because the value you have stored in the session is a completely new value made using the value of the $username variable. As soon as it has been created, the value in the session is not associated with the $username variable whatsoever.
You can store the name and the phrase in the session separately, so they can be modified independently, and then combine them together later at the time you need to use them together.
For the specific case in your comment, storing the SQL string for a prepared statement with placeholders should work.
$_SESSION['statement'] = "SELECT some_columns FROM some_table LIMIT ?, ?";
$_SESSION['limit'] = $limit;
$_SESSION['offset'] = $offset;
You can't store the prepared statement itself, but you can store the SQL string, and then prepare and execute it in subsequent pages.
$stmt = $pdo->prepare($_SESSION['statement']);
$stmt->execute([ $_SESSION['limit'], $_SESSION['offset'] ]);
Just remember when you are ready to bind values to it on your next page before executing it that you need to specify that they should be bound as integers or disable emulated prepared statements.
If you want to add new element in the session array then you can push new element in the session array as follows:
array_push($_SESSION['data'],$element)
You could do something like this:
$username = 'john';
$_SESSION['data'] = 'echo "Hello $username";';
$username = 'mike';
eval($_SESSION['data']);
But I don't know why you'd want to, there are millions of ways you could achieve the results you want, an approach like this probably isn't the best.

Session array not unset

I want to unset session array but It is not happening.
Where am I wrong in this?
if(isset($_SESSION['id']) && isset($_POST['processorder']))
{
$chk = $_SESSION['id'];
$query="update order_details set process_order='1' where id IN(".implode(',',$chk).")";
mysql_query($query) or die(mysql_error());
unset($chk);
}
$chk = $_SESSION['id'];
What you're doing here is creating a variable $chk with the value $_SESSION['id'] then unsetting this $chk but you've never touched the $_SESSION var.
To do so you need to have the following code :
$_SESSION['id'] = '';
unset($_SESSION['id']);
use php unset like that :-
unset($_SESSION['id']);
unset($_SESSION['processorder']);
or you can use session_destroy()
will delete ALL data associated with that user.
Not this unset($chk);
$chk is just a reference varialble. You need to unset the original variable.
unset($_SESSION['id']);
Use NULL and unset to remove the saved values in $_SESSION[] variables, like:
$_SESSION['id'] = NULL;
unset($_SESSION['id']);
If you put
$_SESSION['id'] = '';
and in case there is space in between '' two quotes, then
if(isset($_SESSION['id'])){}
returns true instead of false.
NOTE: You can also use session_destroy() function, but it destroy all saved session data.
Unsetting $chk doesn't actually affect the original array. You could use references to do that. But keep in mind that unsetting a reference itself doesn't affect the original array either. This should work:
$session = &$_SESSION;
unset($session[id']);
This could be useful if you need to perform a number of actions on the $_SESSION - should make your code a bit more readable

Find $_POST variable with same name as other variable

I have a form being passed in $_POST where the names of each field correspond with data in a database
$_POST['test']; (has a value of 1)
$_POST['prod']; (has a value of 2)
Both test and prod are unique names in the database. Is there a way I can dynamically grab a $_POST variable? For example (some code that doesn't work)
$getServerIDs = $link->query("SELECT * FROM servers");
while($row = $getServerIDs->fetch_assoc()){
$serverName = $row['name'];
$newDisplayID = $_POST['$sName'];
$updateDisplayID = "UPDATE servers SET displayID = $newDisplayID WHERE name = $servername";
$runQuery = $link->query($updateDisplayID);
The $_POST['$sName'] is the line of code being the problem. Whats the best way to fix this?
The problem is with line $newDisplayID = $_POST['$sName']; you used single quote and when you put variable in single quote then it is not parsed by php use $_POST[$sName]; or $_POST["$sName"];
Edited
DEMO
Dont use quotes OR use double quotes.
Also be carefull you are using highly insecure code. Google sql injection
You can use array_keys() to get all keys inside and array as $_POST.
$keys = array_keys( $_POST );
But be aware, that your user could add any key there in their submission. So you should in any case filter and sanitize this input!
Down the line you could then use this $keys array to do your output.

How to only update an sql table column if a variable is not empty with php?

I am getting my variables from form fields using php :
$url=$_POST['url'];
$tags=$_POST['tags'];
$skillArea=$_POST['skill_area'];
$description=$_POST['description'];
$slideshowImageFileName=($_FILES['imageNameSlideshow']['name']);
But when I run my sql insert query, I get an error if one of the variables is empty, so I have taken to write if statements to deal with this to rewrite the query string, but surely, that's not the answer? It seems very messy
if(empty($slideshowImageFileName)){
$query1="INSERT INTO portfolio (item_name,image_path,description,url) VALUES('$itemName','$imageFileName','$description','$url')";
}else{
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
}
I suppose you are looking for something like this:
$slideshowImageFileName = (isset($_FILES['imageNameSlideshow']['name']) && !empty($_FILES['imageNameSlideshow']['name'])) ? $_FILES['imageNameSlideshow']['name'] : NULL;
This will check if the name of the slideshowimage is set and not empty. if it is NULL will be assigned to the variable, if its correct the value will be assigned.
You could replace NULL with "" if you want an empty string to be added.
Try to set the value of $slideshowImageFileName to empty string or a single space as your database table will accept, and use the second query always.
if(empty($slideshowImageFileName)){
$slideshowImageFileName = "";
}
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
I am agreed with Mr. Ray. But there is another solution apart from that. Probably slideshow_image_path field on the table doesn't allow null. So you may change the attribute by allowing null and it will work.
I'd probably construct a builder if I'm sure I'll get a lot of optional data.
Like this:
$acceptedKeys = array
('item_name',
'image_path',
'description',
'url',
'slideshow_image_path');
$inserts = array();
foreach($_GET as $key => $var) {
if(in_array($key, $acceptedKeys)) {
// clean and validate your keys here!
$inserts[$key] = $var;
}
}
$customKeys = implode(array_keys($inserts), ',');
$customValues = implode($inserts, ',');
$query = "INSERT INTO portfolio ($customKeys) VALUES($customValues)";
There's a few options to this.
Simplest one is to make sure the variables are always set, even if not passed through:
//Set up your database connection as normal, check errors etc.
$db = mysqli_connect($host,$user,$password,$db);
$url = isset($_POST['url']) ? mysqli_real_escape_string($db, $_POST['url']) : "";
$tags= isset($_POST['tags']) ? mysqli_real_escape_string($db, $_POST['tags']) : "";
Escaping data is good practice :) In your INSERT query you'll still need to wrap the values in quotes, or you could do that in the above code as per your preference.
http://uk3.php.net/manual/en/mysqli.construct.php

Categories