How to Maintain Session in Curl in PHP

Keeping session alive with Curl and PHP

You also need to set the option CURLOPT_COOKIEFILE.

The manual describes this as

The name of the file containing the cookie data. The cookie file can
be in Netscape format, or just plain HTTP-style headers dumped into a
file. If the name is an empty string, no cookies are loaded, but
cookie handling is still enabled.

Since you are using the cookie jar you end up saving the cookies when the requests finish, but since the CURLOPT_COOKIEFILE is not given, cURL isn't sending any of the saved cookies on subsequent requests.

php - maintain session across curl requests

I'm struggling to imagine how this runs at all.

However these session variables do not reflect in the calling process after curl_close()

Using the default session handler, a second script should just timeout if it is called from something like....

session_start();
...
curl_exec(); // at this point session file is still locked
...
[session_close();]

$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';

eh? You don't specify a path for a cookie in an HTTP request (you do in a response). This will tell the script that the client has a cookie named "path".

Really this should be....

$strCookie = session_name() . "=" . session_id();

However these session variables do not reflect in the calling process after curl_close()

Did you reload the session from storage? (see also previous note about session file locking). Your code should do something like....

session_start();
...
session_close();
...
curl_exec();
...
session_start();

it would be cleaner to switch to a non-blocking handler, or better yet don't pass state via the session - POST the data to the second script read the response from the output stream.

how to retain session when sending second request in curl php?

Tell cURL to use cookies:

curl_setopt(CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt(CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

This way the default Node/Express session cookie based authentication should work since session cookie will be saved upon login and sent with subsequent requests.

http://php.net/manual/en/function.curl-setopt.php

How to maintain cURL HTTP session without storing a cookie?

You can use php://memory stream to save session information in memory instead of a filesystem, if you cannot use the filesystem.

Alternatively, you can parse a session id from response Set-Cookie header on first request, save it to a variable and send it in a Cookie header or by means of CURLOPT_COOKIE on every subsequent request.

How to keep curl session alive between two php processes?

I figured out how it works)
If you want to keep session just copy set-cookie option from header response to some file. After that you can use this cookies for next connection. You have not to do authorization again.



Related Topics



Leave a reply



Submit