We help IT Professionals succeed at work.

Put POST values into cookies.

Jazzy 1012
Jazzy 1012 asked
on
127 Views
Last Modified: 2017-04-12
I get these variables from a form from a pervious page, how can I turn them into cookies so even if I go back they would stay? because now when I go back from the button, it doesn't show anymore
$value1 = $_POST['select_time1'];
$value2 = $_POST['select_time2'];
$value3 = $_POST['select_time3'];
$value4 = $_POST['select_time4'];
$value5 = $_POST['select_time5'];
$value6 = $_POST['select_time6'];

$protien_id = $_POST['protiens'];
$monday = $_POST['mon'];
$tuesday= $_POST['tues'];
$wednesday= $_POST['wed'];
$thursday = $_POST['thur'];
$friday = $_POST['fri'];

Open in new window

Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
You might want to put them into the session array for short-term storage, or store them in a database for longer-term storage.  There is no design pattern that puts meaningful data into a cookie.  Cookies are like database keys -- they are pointers to the information, not the information itself.

Here's an article about the PHP session.  HTH, ~Ray
https://www.experts-exchange.com/articles/11909/PHP-Sessions-Simpler-Than-You-May-Think.html
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
Firstly I would put all those values in the form into an array - say data
data[select_time1]
data[select_time2]
...

Now you can do the following. The code below will check both POST and SESSION for a data element. The first one found is used - if none is found an empty array is used. This is then merged with the default values so the result is a filled array that has the correct values
<?php
session_start();
$default = array(
  'select_time1' => '',
  'select_time6' => '',
  'protiens' > '',
  'mon' => '',
  'fri' => ''
);

$data = loadData($default);
print_r($data);
/*
  This function gets the data from the post - if there is none
  it gets the data from the Session - if there is none it 
  defaults to an empty array.

   It then loops through supplied default array and merges the
   values from the default with those it already has from POST
   or Session. It returns an array that is guaranteed to have values
   for all the required values - obtained either from POST or  Session
   in that order
*/
function loadData($default)
{
  $data = !empty($_GET['data']) ? $_GET['data'] : false;
  if ($data === false) {
     $data= !empty($_SESSION['data']) ? $_SESSION['data'] : array();
  }
  
  foreach($default as $key => $value) {
    if (!isset($data[$key])) {
       $data[$key] = $value;
    }
  }
  $_SESSION['data'] = $data;

  return $data;
}

Open in new window

Most Valuable Expert 2011
Author of the Year 2014

Commented:
If I'm not misunderstanding the question, the values are already in an array -- it's $_POST that contains the request variables.

Maybe something along the lines of this design would be helpful.  It seems to handle both form validation and remembering the good values, and on my Chrome browser, it handles the "back" button sensibly.  Haven't tested it on other browsers.
https://iconoun.com/demo/form_highlight_errors.php
<?php // demo/form_highlight_errors.php
/**
 * Demonstrate how to highlight errors in form input, and remember valid inputs
 * Client is asked to put in a value
 * If the value fails our test we show an error message
 * We put a marker next to the input control on the form
 * We turn the form border red
 * SEE http://www.w3schools.com/CSS/pr_class_visibility.asp
 */
error_reporting(E_ALL);


// THESE STYLE ELEMENTS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = $error_xyz = $error_any = 'hidden';
$boxer_abc = $boxer_xyz              = 'black';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = isset($_POST["abc"]) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = isset($_POST["xyz"]) ? trim(strtoupper($_POST["xyz"])) : NULL;


// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        // VALIDATION FAILED
        $error_abc = $error_any = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        // VALIDATION FAILED
        $error_xyz = $error_any = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS - ALL VALIDATION PASSED";
        die();
    }

    // OTHERWISE... OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<br>
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<br>
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
it's $_POST that contains the request variables.
Yes but you have to test and access each one at a time. If you use a form array you can get them in one go.
Most Valuable Expert 2011
Author of the Year 2014

Commented:
How about this?
<?php
session_start();
$_SESSION['POST'] = $_POST;

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
Personal preference - I bring all form data (that needs to be validated, saved to db) in an array - I know that everything I need should be in there and I don't have to unset anything. I can then set other POST variables for control / routing etc that don't interfere with the form data. Allows for quick extraction of a subset of $_POST without having to go through the POST array - as I said personal preference - I use it extensively and it works for me in the frameworks I use.

Author

Commented:
The variables all contain the values I need. I just have a trouble time switching through the page because when I click on a button it takes me back, therefore the session is gone because I'm back to the first page. This is why I want to store my sessions into a cookie so they won't go, when I switch through the pages.

Author

Commented:
Also I have a form that I allow users to keep submitting, how can I append the form values into the session as well?
For example:

$protien when I first submit the form i chose chicken. Then later I want to chose another protien from a different meal so I click lamb. how can I make the protien get the lamb but still have chicken inside it?

like:
$protien = 'chicken'
$protien - 'chicken', 'lamb' //after i post form again
Most Valuable Expert 2011
Author of the Year 2014

Commented:
therefore the session is gone because I'm back to the first page
If this is really happening to you, there is something else going wrong in your application.  Please read the article about how sessions work.  It is required knowledge for PHP developers.  The session, once established, should remain in place as long as you're still on the same web site.  If it's losing data when you "go back" you almost certainly have a design flaw or logic error in your app.
Most Valuable Expert 2011
Author of the Year 2014
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Sessions allow you to store complex types (Arrays and Objects)
Sometimes, but not always.  Please see the cautionary note here:
http://php.net/manual/en/ref.session.php#120110
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
Yes stdClass is a special case - and for other objects you need to include the Class file so that PHP knows how to interpret the data.

The point is that the serializing into and out of the session is handled by PHP whereas with a Cookie - you have to do it yourself.
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Yeah, PHP has not got all of this right yet.  Instead of serializing, JSON-encoding may be a better choice sometimes.  Wish this were a magic answer, but it's PHP, and so it's not ever going to be a magic answer. Anyway, you've got an answer and some links to the essential learning resources, so I'll sign off now.  Good luck with your project!
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.