Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Redirection with Post Parameters

I have a webpage. This webpage redirects the user to another webpage, more or less the following way:

<form method="post" action="anotherpage.php" id="myform">      <?php foreach($_GET as $key => $value){     echo "<input type='hidden' name='{$key}' value='{$value}' />";     } ?>  </form> <script>      document.getElementById('myform').submit();  </script> 

Well, you see, what I do is transferring the GET params into POST params. Do not tell me it is bad, I know that myself, and it is not exactly what I really do, what is important is that I collect data from an array and try submitting it to another page via POST. But if the user has JavaScript turned off, it won't work. What I need to know: Is there a way to transfer POST parameters by means of PHP so the redirection can be done the PHP way (header('Location: anotherpage.php');), too?

It is very important for me to pass the params via POST. I cannot use the $_SESSION variable because the webpage is on another domain, thus, the $_SESSION variables differ.

Anyway, I simply need a way to transfer POST variables with PHP ^^

Thanks in advance!

like image 655
arik Avatar asked May 19 '10 12:05

arik


People also ask

Can POST requests be redirected?

in response to a POST request. Rather, the RFC simply states that the browser should alert the user and present an option to proceed or to cancel without reposting data to the new location. Unless you write complex server code, you can't force POST redirection and preserve posted data.

What is redirect () in PHP?

PHP. Redirection allows you to redirect the client browser to a different URL. You can use it when you're switching domains, changing how your site is structured, or switching to HTTPS. In this article, I'll show you how to redirect to another page with PHP.


1 Answers

You CAN header redirect a POST request, and include the POST information. However, you need to explicitly return HTTP status code 307. Browsers treat 302 as a redirect with for GET, ignoring the original method. This is noted explicitly in the HTTP documentation:

  • https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8

Practically, this means in PHP you need to set the status code before the redirect location:

    header('HTTP/1.1 307 Temporary Redirect');     header('Location: anotherpage.php'); 

However, note that according to the HTTP specification, the user agent MUST ask user if they are ok resubmitting the POST information to the new URL. In practical terms, Chrome doesn't ask, and neither does Safari, but Firefox will present the user with a popup box confirming the redirection. Depending on your operating constraints, maybe this is ok, although in a general usage case it certainly has the potential to cause confusion for end users.

like image 90
Charles Avatar answered Sep 22 '22 12:09

Charles