Home » Php » post – PHP cURL says Moved Permanently when POSTing to a virtual host

post – PHP cURL says Moved Permanently when POSTing to a virtual host

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to POST some data with PHP cURL to a local site that’s using virtual hosts to have a custom domain http://example.local, but the result seems to be a Moved Permanently. How could I get this to work?

This is my current code:

$url = "http://example.local/paypal_ipn.php"
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);

curl_setopt($ch,CURLOPT_POST, substr_count($req,'&')+1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $req);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

I’ve tried to set CURLOPT_FOLLOWLOCATION as true, but that just follows without the POST data.

How to&Answers:

Use CURLOPT_CUSTOMREQUEST instead of CURLOPT_POST like;

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");

And one more thhing, you need to add

curl_setopt($curl, CURLOPT_POSTREDIR, 3);

3 means follow redirect with the same type of request both for 301 and 302 redirects.

By doing this, second request will be as POST request as well. Note that, CURLOPT_POSTREDIR implemented in PHP 5.3.2 here

Answer:

try it

//** add options **//

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, "your_var");
curl_setopt($curl, CURLOPT_POSTREDIR, 3);

curl_exec($curl);