通过curl将会话信息传递给PHP

What I'm trying to do is make the session from the client program available to the server program.

Both programs are running on the same Apache site, so the configuration for the session files, permissions, etc are all the same.

Test server program:

<?php
session_name('main');
session_start();
echo '<pre>'.print_r($_COOKIE, true).'</pre>';
?>

Test client program:

<?php
session_name('main');
session_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIE, 'main='.session_id());
curl_setopt($ch, CURLOPT_POSTFIELDS, 'A=1&B=2');
$result=curl_exec($ch);
curl_close($ch);
echo $result;
?>

Behavior:

  • As written, the curl call to the server times out.
  • If I remove session_start() from the server, the server returns the cookie value as expected.
  • When I remove curl_setopt($ch, CURLOPT_COOKIE, 'main='.session_id()) from the client every call to the server creates a new session file as expected.
  • I added curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile) making sure that $cookiefile exists and is writable, no change in behavior.

So is this just not possible to do? I don't need to write any cookies or get cookie information back, I just need the server program to be able to access same session information as the client.

After a lot more searching I discovered the cause. The client script has the session file locked, so the server session cannot read it, hence the time out. More here: PHP Sessions - Locking and Sharing questions

So doing a session_write_close() in the client solves the issue, and leaves the $_SESSION variable intact, however if using session cookies and output has already happened (client) the session cannot be restarted on the client, so this solution will probably not work for me.

What I will probably need to do is serialize the session manually, put the information in a database table, and pass the key to the server which can read the table, then upon return I can pull the data from the table and update the session in the client.