Problem in accessing sessions variables by multiple threads or files in php

Sep 04, 2014  ยท  4330 views

The session variables in php will be created in files on physical locations.. For each session a file will be created and the session data will be saved in this file with all the session variables and their values.

Eg: $SESSION['name']= 'username';

If a session variable is created and used as shown in the above eg, then the created session file will have the session variable name and its value in it. and in order to access/create sessions within a php file we need to declare in the first line of php file as "sessionstart();" - This statement actually locks the session file for writing.

So no other php file or thread can use this same session file. If any other page is having the line"sessionstart()" (i.e., if it is trying to access session variables)it has to wait until the initial php file which locked the file unlocks it..

If the initial page does not unlock the session file then the second file keeps on waiting and finally the server will throw time out error. This situation is possible when you are making simultaneous ajax calls for dynamic php pages which are using sessions in it.

The solution is..

Seems to be simple but very difficult to track this. It is not possible to make the sessions file to be used by multi threads but we can close the session file once your work with that is completed by using the below line of code.


This line will close the session file and makes it available for other threads/pages. Hence, if any other page is waiting for the session file it can access it without waiting for the complete execution of first page.

So it would be better if we save the required session data in some other local variables just afterthesessionstart() statement and close the session once we have used it.

Any better solution for this is appreciable!!!



A Software Engineer by profession, a part time blogger and an enthusiast programmer. You can find more about me here.

Post a comment

Thank you! You are now subscribed.

Sign up for our newsletter

Subscribe to receive updates on our latest posts.

Thank you! You are now subscribed.