DrXCheng
DrXCheng

Reputation: 4132

passing a variable after POST in PHP

I have a index.php in the root folder dealing with all the commands. In page of url "root/?a=a&b=b", I have a form for POST to add new item.

After submit the form, the page should be back to "root/?a=a&b=b" and a new item is shown (I currently use header('Location: ' . $_SERVER['HTTP_REFERER'])).

In the meantimes, there is a div in page "root/?a=a&b=b". If the page comes back from submitting the form, it should be shown; otherwise (GET to this page), it should be hidden.

I currently add a "&success=true" at the end of the the url. But after submitting the form, there is a "&success=true" in the url, and if I refresh the page, although not coming back from submitting form, the div is still shown.

I wonder if there is a way to pass a variable instead of modifying the url after submitting the form. In addition, I don't want to use $_SESSION.

Thanks for helping!

Upvotes: 0

Views: 213

Answers (3)

SystemParadox
SystemParadox

Reputation: 8647

This answer assumes that you are POSTing and redirecting back without any user intervention. If user action is required on the form processing page then most of this will not apply...

Almost all of the forms I write post to the same URL (use action=""). This does make life much easier. I would strongly discorage any use of HTP_REFERER, as it's an optional field that is totally reliant on the browser. Most do not send referers, or only send them in certain circumstances.

I would also urge you to reconsider whether it is really necessary to redirect from the form processor. I suspect you're doing it to stop the user reposting the same thing accidentally, but all modern browsers pop up a sane message if the user tries to refresh a POST request so this shouldn't be necessary. If you don't redirect from the form processor then you can show the success message on the processing page, which eliminates any need to use COOKIE or SESSION.

Upvotes: 0

Ilia Sachev
Ilia Sachev

Reputation: 76

On the page where you want to show a hidden div, you need to check referer too

If you come to this page from page with form, you must show div, else don't show

You also can do this by checking REQUEST_METHOD to url "root/?a=a&b=b" For example

if($_SERVER['REQUEST_METHOD'] == 'GET'){
  // do what you wonna to do
  $showForm = false;
} else if($_SERVER['REQUEST_METHOD'] == 'POST'){
  // There is an action of submitting your form.
  // Do this, after that show info
  $showForm = true;
}

if($showForm){
  echo '<div id="hiddenDiv">Hello hidden div</div>';
}

Upvotes: 0

AndreKR
AndreKR

Reputation: 33678

This is a common problem and the cleanest method I know to work around this when using Post-Redirect-Get is to set a cookie in the response to the POST and then immediately delete it in the response to the GET.

Upvotes: 2

Related Questions