How do I prevent to be redirected with PHP cURL

Additional to the measures provided on the accepted answer, also make sure you are escaping the output if you are echoing it.

For example, Instead of:

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

Use:

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

This solved the issue in my case cause there was a JS redirect on the response I was getting.

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


Try this:

  <?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);
?>

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

will not output result

and

curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);

will ignore redirects (so when http://google.com/ transfers you to https://google.us/ this will ignore it)

Tags:

Php

Curl