开发者

Ajax progress with PHP session

开发者 https://www.devze.com 2022-12-31 06:10 出处:网络
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

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开发者_Python百科-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'];


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

0

精彩评论

暂无评论...
验证码 换一张
取 消