Question

I want to write a chat system. I have used ajax, php and the commet porotocol.

everything is ok , but there is a problem with session: when session is started on the top of the script, everything goes wrong (my script can't underestand there is a new msg so I must wait for the sleep time to end)

this is a simple version of my php file :

   $filename  = dirname(__FILE__).'/data.txt';

// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
  file_put_contents($filename,$msg);
  die();
}
// infinite loop until the data file is not modified
$lastmodif    = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
  usleep(10000); // sleep 10ms to unload the CPU
  clearstatcache();
  $currentmodif = filemtime($filename);
}

// return a json array
$response = array();
$response['msg']       = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
Was it helpful?

Solution

That's because sessions are locking, the only way to avoid this is by calling session_write_close() before your usleep command.

Basically, if one script uses sessions, no other script can run at the same time, for the same client using the same web browser until the first script finishes or calls session_write_close(). This is because PHP uses locking, and sees the session file is locked, and will wait for it to become available again before running your script.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top