开发者

PHP Readfile() number of bytes when user aborted

I'm using a PHP script to stream a live video (i.e. a file which never ends) from a remote source. The output is viewed in VLC, not a web browser. I need to keep a count of the number of bytes transferred. Here is my code:

<?php

ignore_user_abort(true);
$stream = $_GET['stream'];

if($stream == "vid1")
{
    $count = readfile('http://127.0.0.1:8080/');
    logThis($count);
}

function logThis($c)
{
    $myFile = "bytecount.txt";
    $handle = fopen($myFile,'a');
    fwrite($handle,"Count: " . $c . "\n");
    fclose($handle);
}

?>

However it appears that when the user presses the stop button, logThis() is never called, even though I've put in ignore_user_abort(true);

Any ideas on what I'm doing wrong?

Thanks

Update2: I've changed my code as I shoudn't be using ignore_user_abort(true) as that would continue to download the file forever even after the client has gone. I've changed my code to this:

<?php

$count = 0;

function bye()
{
    //Create Dummy File with the filename of equal to count
}

register_shutdown_function('bye');
set_time_limit(0);
ignore_user_abort(false);

$stream = $_GET['stream'];

if($stream == "vid1")
{
    $GLOBALS['count'] = readfile('http://127.0.0.1:8080/');
    exit();
}

?>

My problem now is that when the script is aborted (i.e. user presses stop), readfile won't return a value (i.e. c开发者_StackOverflow社区ount remains at 0). Any ideas on how I can fix this?

Thanks


When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.

so setting the set_time_limit to 0 should help.


Ok folks I managed to fix this. The trick was to not use readfile() but read the video stream byte by byte. Ok it may not be 100% accurate, however a few bytes inaccuracy here or there is ok.

<?php

$count = 0;

function logCount()
{
    //Write out dummy file with a filename equal to count
}

register_shutdown_function('logCount');
set_time_limit(0);
ignore_user_abort(false);

$stream = $_GET['stream'];

if($stream == "vid1")
{

    $filename = 'http://127.0.0.1:8080/';
    $f = fopen($filename, "rb");

    while($chunk = fread($f, 1024)) {
        echo $chunk;
        flush();
        if(!connection_aborted()) {
            $GLOBALS['count'] += strlen($chunk);
        }
        else {
            exit();
        }
    }
}

?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜