title: Keeping session alive with Curl and PHP
body: <p>I'm trying to connect to an API, authenticate a user and then view the user details. This is accomplished by first accessing the login endpoint at</p>
  
  <pre><code>http://api.example.com/login/&lt;username&gt;/&lt;password&gt;
  </code></pre>
  
  <p>to log in and then the following to view user details:</p>
  
  <pre><code>http://api.example.com/user/
  </code></pre>
  
  <p>This all works in a web browser. However, once I try to use Curl, the login works fine, but when attempting to view user details, I get back a 401, unauthorized error. I believe this is because Curl isn't saving the session cookies properly? Can someone point out why it isn't working and how to fix it? I've tried searching stack exchange, however, none of the solutions I've tried have worked for my situation. The code I'm using to curl the endpoints is shown below. Thanks!</p>
  
  <pre><code>define("COOKIE_FILE", "cookie.txt");
  
  // Login the user
  $ch = curl_init('http://api.example.com/login/joe/smith');
  curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, true);
  echo curl_exec ($ch);
  
  // Read the session saved in the cookie file
  echo "&lt;br/&gt;&lt;br/&gt;";
  $file = fopen("cookie.txt", 'r');
  echo fread($file, 100000000);   
  echo "&lt;br/&gt;&lt;br/&gt;";
  
  // Get the users details
  $ch = curl_init('http://api.example.com/user');
  curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, true);
  echo curl_exec ($ch);
  </code></pre>
  
  <p>This code will output:</p>
  
  <pre><code>HTTP/1.1 200 OK Date: Mon, 22 Oct 2012 21:23:57 GMT Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.14 Set-Cookie: cfapi=f481129c9616b8f69cc36afe16466545; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Type: application/json X-Powered-By: CFWAPI 0.1a Content-Length: 46 {"status":200,"msg":"Successfully Logged In."}
  
  # Netscape HTTP Cookie File # http://curl.haxx.se/rfc/cookie_spec.html # This file was generated by libcurl! Edit at your own risk. api.example.com FALSE   /   FALSE   0   cfapi 94f63b07ccf7e34358c1c922341c020f 
  
  HTTP/1.1 401 Unauthorized Date: Mon, 22 Oct 2012 21:23:57 GMT Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.14 Set-Cookie: cfapi=a8eb015a7c423dde95aa01579c4729a4; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Type: application/json X-Powered-By: CFWAPI 0.1a Content-Length: 49 {"status":401, "msg":"You need to login first!"}
  </code></pre>