I ran into an issue at the end of last week regarding sessions in PHP. The problem was the locking that happens over the sessions. This isn’t what’s now coded in place, but it was a thought I had (bad idea). So I had a PHP file which did a POST to another file – using the following code
function do_post_request($url, $data, $optional_headers = null) { $params = array('http' => array('method' => 'POST','content' => $data)); if ($optional_headers !== null) { $params['http']['header'] = $optional_headers; } $ctx = stream_context_create($params); $fp = fopen($url, 'rb', false, $ctx); if (!$fp) { throw new Exception("Problem with $url, $php_errormsg"); } $response = stream_get_contents($fp); if ($response === false) { throw new Exception("Problem reading data from $url, $php_errormsg"); } return $response; }
The receiving page will start off its own session and to try to access the globals in the original session, I tried assigning the sessionid to the new page before calling session_start();.
session_id($_GET['SESSIONID']); session_start();
What happens is the first page will take a long while before timing out. Behind the scenes, the first PHP page is WAITING for the POST to return, whilst having locked the session variables as already being accessed. The receiving page then tries to “resume” this session and starts to wait for the session variables to be unlocked before so they can be read.
There is the ability to call session_write_close() but this will set the session variables to read only and you will not be able to write to them.
Written by Milton Lai