duancui19840401 2010-12-26 02:11
浏览 40
已采纳

PHP Readfile()用户中止时的字节数

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 . "
");
    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. count remains at 0). Any ideas on how I can fix this?

Thanks

  • 写回答

3条回答 默认 最新

  • douyi3833 2010-12-26 04:16
    关注

    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();
            }
        }
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条