curl : How to set PHPSESSID in the request headers of a call, how to solve waiting and getting no response
I have been trying to use curl in PHP to post some data in some page of mine that requires login and thus a session to be present.
So i had to send the session along with the curl request. The problem was that the script seemed to be waiting for a response.
What happened actually was that my target script was waiting for the session to become available.
As is stated in session_write_close():
“session data is locked to prevent concurrent writes only one script may operate on a session at any time”
So my target script was waiting for the session to become writable while the current script (that made the post ) couldn’t complete because it was waiting the response of the target (cruel things the deadlocks). The solution is to call session_write_close() and free the session before you make the call curl_exec()
That’s it. Take a look at the following code. Take care.
$ch = curl_init();
die('Failed to init curl ...');
curl_setopt($ch, CURLOPT_URL, "https://example.org/subdir/something.php" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); //remove this line if you want submit text/html
$strCookie = 'PHPSESSID=' . session_id() . '; path=/';
curl_setopt( $ch, CURLOPT_COOKIE, $strCookie ); //We set our session in the headers of the request!
session_write_close(); //kmak - this is what makes the session transmission possible ... otherwise we will wait and wait ...
die("Failed in curl_exec with error:".curl_error($ch));