Keywords: PHP | redirect | POST | data transmission | HTTP | cURL | JavaScript
Abstract: This article explores the limitations of sending POST data via PHP redirects and presents workarounds such as using cURL, generating HTML forms with JavaScript, and alternative methods. The focus is on the accepted answer's insight that direct POST redirects are not possible with PHP's header function.
Introduction
The question addresses a common scenario in web development where data needs to be sent to an external gateway via POST without using HTML forms. In PHP, sending data via GET with a redirect is straightforward using the header function, but POST presents challenges.
Understanding the Limitation
As per the accepted answer, PHP cannot directly send POST data via a redirect because HTTP redirects (e.g., using header('Location: ...')) are designed for GET requests. When a browser receives a redirect, it typically issues a new GET request, losing any POST data.
Primary Solutions
Two main approaches are discussed:
Using cURL
With cURL, the PHP script acts as an HTTP client, sending a POST request directly to the target URL. This method bypasses the browser but requires the script to handle the response.
Generating HTML Form with JavaScript
A workaround is to generate an HTML form dynamically using PHP and use JavaScript to submit it automatically. This mimics a POST request from the browser.
Example code adapted from Answer 2:
function redirect_post($url, array $data)
{
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function closethisasap() {
document.forms["redirectpost"].submit();
}
</script>
</head>
<body onload="closethisasap();">
<form name="redirectpost" method="post" action="<? echo $url; ?>">
<?php
if ( !is_null($data) ) {
foreach ($data as $k => $v) {
echo '<input type="hidden" name="' . $k . '" value="' . $v . '"> ';
}
}
?>
</form>
</body>
</html>
<?php
exit;
}
Alternative Methods
Other answers suggest using sessions with HTTP 307 status code, but these have limitations such as dependency on session handling and potential issues with request headers.
Conclusion
In summary, while PHP cannot natively redirect with POST data, practical solutions exist. The choice depends on the specific use case: cURL for server-side requests or JavaScript-based forms for browser-centric approaches.