Redirect with Curl

Asked

Viewed 335 times

1

I’m trying to log in to a Curl account but it doesn’t go to the final page.

Site map:

  1. form page.
  2. page that receives the post (Curl is stopped here). 200 OK
  3. restricted page(Curl does not arrive here). 302 Object Moved

someone knows why Curl does not access this page or go through it?

My code.

$f = fopen('cookies.txt', 'w');
$fp = fopen("cookies.txt", "w");
fclose($fp);


 $url = "";

 $postfields = array();
 $postfields[''] = '';
 $postfields[''] = ''; 
 $postfields[''] = '';
 $postfields[''] = ''; 
 $postfields[''] = '';
 $postfields[''] = ''; 
 $postfields[''] = '';
 $postfields[''] = '';

 $tmpfname = dirname(__FILE__).'/cookies.txt';

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 //curl_setopt($ch, CURLOPT_COOKIESESSION, true);
 curl_setopt($ch, CURLOPT_HEADER, 1);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
 curl_setopt($ch, CURLOPT_TIMEOUT, 120);
 curl_setopt($ch, CURLOPT_POST,true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
 //curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array()));
 //curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
 curl_setopt($ch, CURLOPT_POSTREDIR, -1);
 curl_setopt($ch, CURLOPT_VERBOSE, 1);
 curl_setopt($ch, CURLOPT_MAXREDIRS, -1);
 //curl_setopt($ch, CURLOPT_AUTOREFERER, true);
 curl_setopt($ch, CURLOPT_STDERR, $f);
 curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname );
 curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname );
 //curl_setopt($ch, CURLOPT_REFERER, $url);
 $redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );
 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 $status_url = curl_getinfo($ch , CURLINFO_EFFECTIVE_URL);
 curl_setopt($ch, CURLOPT_ENCODING, "");
 $err = curl_error($ch);
 //ob_start();
 $ret = curl_exec($ch); // Get result after login page.
 $redirectedUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
 curl_close ($ch);

  echo $ret;
  • This option -> curl_setopt($ch, CURLOPT_POSTREDIR, -1) is really necessary?

1 answer

1

You need to set the CURL parameter, where it allows it to follow redirects:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Since you wanted to limit redirects you can use this parameter:

curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
  • I’ve done it @Dante, but it doesn’t do the directing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.