How to send post data to any url (with redirection) without using curl or fsocket in php
I would like my page to be redirected to new url with some post data being sent to it. I don't want to use curl or fsocket because they will not redirect user to that new url.
Is there any alternative for header("Location: blahblahblah"); to send post data? I tried with document.form.submit(); and it worked but some users are facing problem with javascript.
Can any one provide alternate solution for this?开发者_JAVA百科 Is there any php function to redirect user to new url along with some post data being sent to this url.
Thanks in advance.
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
Have a look at this link http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
the canonical way to do a redirect is with javascript, right? you need to have a simple page where you :
a) generate a form with the action url being the place you want to go
b) write hidden fields to contain your post_data
c) have javascript submit your form for you on load
You can't mimic the behaviour of a form using PHP. You may send POST data, but not redirect the user with the same request. You'll need to do it with a form. As Igor describes, it's possible to change the expected behaviour of forms with Javascript but I'd recommend against it.
What's wrong with using header("Location: $new_url")
? That is performing a redirect and is the right way to do it AFTER POST
ing data.
Edit: Updated to clarify that this is not how data is posted.
Alternative solutions if you just need to transfer data but POST is not mandatory:
- redirect user and transmit data via query string
- save data in a session and redirect user
精彩评论