title: login via curl and reusing cookie for a second request
body: <p>I'm trying to login via curl, and after the login make a second request with the generated cookie. But It doesn't work, I'm not logged in. How can I keep the cookie and reuse it?</p>
  
  <p>Here is my code:</p>
  
  <pre><code>&lt;?php
  
  // Define the URL and the data you want to send
  $loginUrl = 'https://domain.tld/login.php';
  $parseUrl = 'https://domain.tld/start.php?page=user';
  $loginVars = array(
      'username' =&gt; 'user',
      'password' =&gt; 'pass'
  );
  
  // Now we try to login at the page
  $login = curl_init();
  
  curl_setopt( $login, CURLOPT_URL, $loginUrl);
  curl_setopt( $login, CURLOPT_POST, 1);
  curl_setopt( $login, CURLOPT_POSTFIELDS, $loginVars);
  curl_setopt( $login, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt( $login, CURLOPT_HEADER, 1);
  curl_setopt( $login, CURLOPT_RETURNTRANSFER, 1);
  
  $loginResponse = curl_exec( $login );
  
  preg_match_all('|Set-Cookie: (.*);|U', $loginResponse, $matches);
  $cookies = implode('; ', $matches[1]);
  
  // No we download another page while reusing the cookie
  
  $parse = curl_init();
  
  curl_setopt( $parse, CURLOPT_URL, $parseUrl);
  curl_setopt( $parse, CURLOPT_FOLLOWLOCATION, 0);
  curl_setopt( $parse, CURLOPT_HEADER, 1);
  curl_setopt( $parse, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt( $parse, CURLOPT_COOKIE, $cookies);
  
  $parseResponse = curl_exec( $parse );
  
  // Create a DOMDocument for parsing the HTML
  $dom = new DOMDocument();
  libxml_use_internal_errors(true);
  $dom-&gt;loadHTML($parseResponse);
  
  // Find the element with an ID of 'username'
  $data = $dom-&gt;getElementById("username");
  echo $data-&gt;nodeValue;
  
  curl_close($login);
  curl_close($parse);
  
  ?&gt;
  </code></pre>
  
  <p>How can I get this working?</p>