views:

191

answers:

1

I have an app that processes images and use jQuery to display progress to the user.
I done this with writing to a textfile each time and image is processed and than read this status with a setInterval.

Because no images are actually written in the processing (I do it in PHP's memory) I thought a log.txt would be a solution, but I am not sure about all the fopen and fread's. Is this prone to issues?

I tried also with PHP sessions, but can't seem to get it to work, I don't get why..

HTML:

<a class="download" href="#">request download</a>
<p class="message"></p>

JS:

$('a.download').click(function() {

    var queryData = {images : ["001.jpg", "002.jpg", "003.jpg"]};       
    $("p.message").html("initializing...");

    var progressCheck = function() {
        $.get("dynamic-session-progress.php",
            function(data) { 
                $("p.message").html(data); 
            }
        );
    };

    $.post('dynamic-session-process.php', queryData,
        function(intvalId) {
            return function(data) {
                $("p.message").html(data);
                clearInterval(intvalId);
            }
        } (setInterval(progressCheck, 1000))
    );

    return false;
});

process.php:

// session_start();

$arr = $_POST['images'];
$arr_cnt = count($arr);
$filename = "log.txt";

for ($i = 1; $i <= $arr_cnt; $i++) {
    $content = "processing $val ($i/$arr_cnt)";

    $handle = fopen($filename, 'w');
    fwrite($handle, $content);
    fclose($handle);

    // $_SESSION['counter'] = $content;

    sleep(3); // to mimic image processing
}

echo "<a href='#'>download zip</a>";

progress.php:

// session_start();

$filename = "log.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

echo $contents;

// echo $_SESSION['counter'];
+2  A: 

What if two clients process images at the same time?

You can try adding session_write_close() between setting the new status in the session, so that the new session data is stored, otherwise it will only get stored once your script finishes.

Another solution would be to save the status in memcache or to use a database, perhaps separate the statuses with a userid or creating an md5 hash on the image data

baloo
indeed, with multiple clients trying to open the same log.txt file for writing will fail, or present the same status message to all the clients.
catchmeifyoutry
I didn't even think about multiple processing... Thanks for that. A solution could be to create logfiles for each client.
FFish
Thanks for the link to session_write_close() Baloo. So I couldn't get the sessions method to work because the session would only be written at the end of the script?
FFish
Okay I got it working now.. In the loop: session_start(); $content = "processing $val ($i/$arr_cnt)"; $_SESSION['counter'] = $content; session_write_close(); Thanks!!
FFish