aidangig
aidangig

Reputation: 189

php $_POST variable is not saving

I currently have some php code on a form action, and it is being updated to the form's next page with

<?php echo $_POST['var here']; ?>

and it is working, but I noticed when Im trying to refresh the page it asks to confirm resubmission. When I resubmit it works in that tab in which it was sumbitted, but in another new tab it does not show the displayed php post variables. I even took it the next step by seeing that when I open the 2nd page after the form action has been submitted the php post variables are gone...

Help!

Thanks!

Upvotes: 0

Views: 2179

Answers (2)

Iwnnay
Iwnnay

Reputation: 2008

This sounds like desired behavior. The $_POST variable should only be filled when the post action is created. If you're looking to store variables across pages you could store it in either the $_SESSION var in PHP or deal with the front end $_COOKIE business. If you're always going to be rendering pages from the backend then $_SESSION is the way to go. It's never too late to read up on cookies and sessions.

The skinny of it is that you're going to want to do something like this:

<?php 
session_start();
if ($_POST['var']) {
  $_SESSION['var'] = $_POST['var'];
}

echo $_SESSION['var'] ?: $defaultValue;

Then you'll notice that the message changes only when you post and won't exist before then.

Upvotes: 0

Michael
Michael

Reputation: 2631

When you submit a form with <form method="post" /> it does a post request to the server, thus populating $_POST. When you open the link in a new tab it is no longer a post request but a get request. That is why you'll see nothing in $_POST.

$_POST — usually from forms
$_GET - from values on the URL (the query string myscript.php?myvar=Joe)

You can find plenty of resource about it. You can start here

If you want to keep the values you can save them to the session:

<?php 
session_start(); // should be at the top of your php

if (isset($_POST['var'])) {
   $_SESSION['var'] = $_POST['var'];
}

$myvar = isset($_SESSION['var']) ? $_SESSION['var'] : "no var";

echo $myvar; 

Now the value is stored in the session so you can visit the page in a new tab and it will still be there.

Upvotes: 1

Related Questions