I am using CURL to download a large file from an external url and save it on my server. This can take up to few minutes. While the download is running I'm using the curl_setopt($ch, CURLOPT_PROGRESSFUNCTION,.. to run anonymous function which periodically updates my $_SESSION['download_progress'] variable with current download info.
Now, all this is happening in upload.php file and while the user is waiting for the file to download I use javascript to request progress.php page which contains the following simple code:
session_start();
echo $_SESSION['download_progress'];
This allows my javascript code to display information about the download progress.
Except it's not working.
The "progress.php" page won't load until the "upload.php" finished loading (in other words both pages load only after the file finished downloading) and this, is not good. The session_start() somehow blocks the "progress.php" page from loading. I use my own server (apache + php 5.4) so I have all admin rights.
How can I solve this problem? I could use some ugly workaround, like writing the download information into a text file instead of session variable and then use the javascript to directly read that text file, but I would rather not do that.
Thanks
You have the classic problem with filesystem-backed sessions. Your upload script locks the session backing file for its duration, so it's impossible to get access to the session information until it releases the lock.
There are several possible solutions here, but the easiest one would be for your upload script to periodically release the session and lock it again; this would leave opportunity for your progress script to read the session in the meantime.
To release the session lock, call
session_write_close
at any point from your upload script. This leaves you without access to session variables until you callsession_start
again later on. You can repeat this cycle as much as you like.There are also other, more capable solutions. For example you could move the progress information to some storage mechanism that does not stay locked for the duration of a script; you can identify each user's information based on their session id (you don't need to start the session to get its ID, if one exists).