10 Jul 23
cURL Post Follow Location And Update Browser Address Bar
Often time, one might be using cURL to perform some post/get operations. Out of all, there’s a scenario where one might want to do a form post and have the user redirected thru the 302 status code issued by the server. This can be easily implemented using cURL, however, there’s a problem — The address bar doesn’t update to the redirected URL. (e.g. Posting a form from “form.php”, and redirected to “result.php”, but then the browser’s address bar remains showing “form.php”).
In order to solve the above problem, here’s a little trick:
<?php
// post param
$param = array('data' => 'abc');
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "form.php");
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $param);
curl_setopt($c, CURLOPT_HEADER, 1);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_exec($c);
// here's the trick
$redirectLocation = curl_getinfo($c, CURLINFO_EFFECTIVE_URL);
header("Location: $redirectLocation");
?>