Mantener la sesión viva con Curl y PHP

Estoy intentando conectarme a una API, autenticar a un usuario y luego ver los detalles del usuario. Esto se logra accediendo primero al punto final de inicio de sesión en

http://api.example.com/login/<username>/<password>

para iniciar sesión y luego lo siguiente para ver los detalles del usuario:

http://api.example.com/user/

Todo esto funciona en un navegador web. Sin embargo, una vez que trato de usar Curl, el inicio de sesión funciona bien, pero al intentar ver los detalles del usuario, obtengo un 401, error no autorizado. Creo que esto se debe a que Curl no está guardando las cookies de sesión correctamente. ¿Alguien puede indicar por qué no funciona y cómo solucionarlo? He intentado buscar el intercambio de pila, sin embargo, ninguna de las soluciones que he probado ha funcionado para mi situación. El código que estoy usando para rizar los puntos finales se muestra a continuación. ¡Gracias!

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 "<br/><br/>";
$file = fopen("cookie.txt", 'r');
echo fread($file, 100000000);   
echo "<br/><br/>";

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

Este código dará salida:

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!"}

Respuestas a la pregunta(4)

Su respuesta a la pregunta