Lunar
Lunar

Reputation: 4711

PHP forward data post

I am trying to forward data from one page to another without using cURL, is this possible?

At the moment i have tried

header('HTTP/1.1 307 Temporary Redirect');
header('Location: new-location.php');

This works nicely but gives a stupid pop up box, any other methods?

I have tried using curl but nothing happens, not sure if its enabled on my server!

Upvotes: 11

Views: 18596

Answers (5)

Celmaun
Celmaun

Reputation: 24762

I think following is the only possible way to achieve that, instead of redirecting with location header, send this html:-

<!DOCTYPE html>
<html>
    <body onload="document.forms[0].submit()">
        <form action="new-location.php" method="post">
            <?php foreach( $_POST as $key => $val ): ?>
                <input type="hidden" name="<?= htmlspecialchars($key, ENT_COMPAT, 'UTF-8') ?>" value="<?= htmlspecialchars($val, ENT_COMPAT, 'UTF-8') ?>">
            <?php endforeach; ?>
        </form>
    </body>
</html>

Upvotes: 14

Bob Ray
Bob Ray

Reputation: 1172

Using cURL or fopen() are common suggestions, but neither actually "forwards" the user to the other page.

To truly forward the user to another page with $_POST data intact, you can create an intermediate page dynamically that contains a form with the post data and JS code that submits the form immediately (along with a button or link to submit the form if the user does not have JS enabled).

You then forward the user to that intermediate page, and it forwards the user to the target page with the #_POST data intact. If the intermediate page has no visible content, the user won't know it's there.

The target page could unlink the intermediate page so there's no chance of a re-submission.

Upvotes: 1

Kim
Kim

Reputation: 165

You could use the following to forward post data to another url. Notice that the response is captured in the $data variable, with which you can do whatever you want.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.domain.tld/urltopostto.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
$data = curl_exec($ch);
curl_close($ch);

Upvotes: 14

Matěj G.
Matěj G.

Reputation: 3115

If I understand the problem correctly and you're working on an Apache server with mod_rewrite enabled, you could use URL rewriting. You could set the request method as a condition and rewrite the original URL to the alternate one:

RewriteCond %{REQUEST_METHOD} ^POST
RewriteRule ^index.php new-location.php [L]

Upvotes: 2

Stephane Gosselin
Stephane Gosselin

Reputation: 9148

Maybe, just maybe you can try it this way:

header("Status: 200");
header("Location: new-location.php");
exit;

Upvotes: -3

Related Questions