I have 2 PHP scripts, one residing on Server A and another on server B. I need to pass variables received via POST by PHP A to PHP B without the page redirecting. How can I do that?
4 Answers
You can use curl,
$curlHandler = curl_init();
$curlOpts = array(
CURLOPT_URL => "http://www.example.com/Target.php",
CURLOPT_FRESH_CONNECT => true,
CURLOPT_HEADER => false,
CURLOPT_POSTFIELDS => http_build_query($_POST, "", "&"),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => "MyScript/0.1"
);
curl_setopt_array($curlHandler, $curlOpts);
if (false===($responseString=curl_exec($curlHandler))) {
exit("0 - No connection to server.");
}
echo $responseString;
If you send POST-Data to this scrip it will send it to http://www.example.com/Target.php.
If it gets $_POST["Foo"] = 10 then it will send $_POST["foo"] = 10 to Target.php.
It uses all Post variables it gets with the same names and values.
EDIT:
If you want to send some vars you can do it like this:
$vars = array("key" => "value",
"key2" => "value2",
...
);
after doing so you have to change the line from the example above:
CURLOPT_POSTFIELDS => http_build_query($_POST, "", "&"),
needs to be changed to
CURLOPT_POSTFIELDS => http_build_query($vars, "", "&"),
3 Comments
$curlHandler = curl_init();?By performing a POST request from within your PHP script. There are lot's of tutorials out there on how to do this (e.g. this one). You just transmit the POST parameter values to the second server this way and there is no need for a page redirect.
Comments
Do you know jquery. It has a simple way of doing exactly what you want. It is very easy to learn. Check on this example http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/