Mysterious Timeouts Explained

2014 年 12 月 16 日3960

PHP Sessions – Mysterious Timeouts Explained

August 11, 2008

patrik

Tags: php

I recently found out something I think worth writing a couple of lines about. Have you ever tried to make a HTTP request from PHP to a second script and preserve the session and ending up with the request hanging? Let me give you an example.

home.php:

session_start();



...



$url = "http://url/admin.php?PHPSESSID=".session_id();



$fp = fopen($url, 'r');



$content = fread($fp); // will hang here!



...

The problem lies in the fact that PHP opens the session file in a exclusive mode, which denies other threads to open the same file. In another words, admin.php will wait for home.php to release the lock on the session file and this will eventually lead to a timeout for the request. But fortunately there is a solution. To solve this you must close the session file before making the request.

home.php:

session_start();



...



session_write_close(); // close the session file so admin.php can access it



$url = "http://url/admin.php?PHPSESSID=".session_id();



$fp = fopen($url, 'r');



$content = fread($fp);



session_start(); // start the session again



...

I hope this will save you some headache!

0 0