开发者

How do I prevent to be redirected with PHP cURL

I'm developing a form in which requires to submit the collected data to a third party website, in the form of: http://www.domain.com/page?key=value&key2=value2

I decide to use cURL as I have not found an alternative that convince me.

The problem that I'm running is that once the form is submitted, cURL is executed but I'm being redirected to the domain that I specified. Instead, I want to redirect the user to a co开发者_JAVA百科nfirmation page within my domain and not to the third party website.

Here is an example of the code that 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 from being redirected to otherserver.domain.com?

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

Thank you all in advance


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜