How to prevent redirection with PHP cURL

I am developing a form in which you want to send the collected data to a third-party website in the form: http://www.domain.com/page?key=value&key2=value2

I decided to use cURL because I did not find an alternative that convinced me.

The problem that I run is that after submitting the form, cURL is executed, but I am redirected to the domain I specified. Instead, I want to redirect the user to a confirmation page in my domain, and not to a third-party website.

Here is an example of the code I'm using:

$URL="otherserver.domain.com"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://$URL"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "key=value2&key2=value2&key3=value3"); curl_exec($ch); $info = curl_getinfo($ch); curl_close ($ch); 

How can I prevent a redirect to othererver.domain.com?

Please feel free to let me know if you think that instead of using cURL there is a better way to send data to a third-party website.

Thanks to everyone in advance.

+9
source share
3 answers

Try the following:

  <?php $url = "http://***.."; $ch = curl_init($url); $opts = array(CURLOPT_RETURNTRANSFER => 1, CURLOP_HEADER => 1, CURLOPT_FOLLOWLOCATION => 0, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => "foo=ba"); curl_setopt_array($ch, $opts); echo curl_exec($ch); ?> 
+5
source
 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 

will not output the result

and

 curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); 

ignores redirects (so when http://google.com/ gives you https://google.us/ it will ignore it)

+5
source

In addition to the measures indicated in the accepted answer, also make sure that you avoid the output if you repeat it.

For example, instead of:

 $lastResponse = curl_exec( $ch ); echo $lastResponse; 

Using:

 $lastResponse = curl_exec( $ch ); echo htmlentities($lastResponse ,ENT_QUOTES); 

This solved the problem in my case, because the answer I received was a JS redirect.

I know this is an old question, but this is the first result online, so I hope this helps someone as I did when I found it on the forum after a couple of hours of searching.

0
source

All Articles