簡體   English   中英

如何檢測用戶是否在php中終止連接

[英]How to detect if user aborted connection in php

我正在嘗試創建php流應用程序。 問題是我不能允許兩個用戶同時連接,因為,好了,他們要為此付費,所以如果他們共享流,那就沒用了。

因此,我的解決方案是在MySQL數據庫中添加一行,以記錄用戶是否以1登錄,並且當用戶停止/取消流記錄時,該記錄將重新設置為0。這就是我無法檢測到的問題用戶中止連接時。 我認為我嘗試了所有事情: ignore_user_abort(true), while(!connection_aborted){readfile($stream)}...

我有多個流文件,但我在這里放了一個我認為最接近解決方案的文件。 O,還有一段時間,它在我沒有使用任何動態流/用戶名/密碼的情況下仍然有效。 因此文件如下:

<?php

require "../general/bootstrap.php"; // Include bootstrap
require "../general/error.php"; // Comertials when error

session_write_close();
ignore_user_abort(TRUE);
set_time_limit(0);

header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in history
header("Content-Transfer-Encoding: binary");
header("Cache-control: no-cache");
header('Pragma: no-cache');

if (count($items) != 3) {
    if (isset($items[1]) && !empty($items[1])) {
        $username = $items[1];
    } else {
        $username = null;
    }
    error("Missing one or more arguments(tv, username, password)!", $username);
}

$channel = (string) $items[0];
$username = (string) $items[1];
$password = (string) $items[2];

if (stream::channel_exists($channel)) {
    if (stream::channel_is_tv($channel)) {
        header('Content-Disposition: attachment; filename="stream.xspf"');
    } else {
        header('Content-Disposition: attachment; filename="stream.m3u"');
    }
} else {
    header('Content-Disposition: attachment; filename="stream.xspf"');
}

if (!stream::user_has_channel($username, $channel)) {
    error("User has requested channel '$channel' that it doesn't have!", $username);
}

if (!user::login($username, $password)) {
    error("Login failed! - probably because of trying to log in from 2 places at the same time or invalid username/password combination!", $username);
}

if (!isset($stream))
    $stream = stream::get_channel_stream($channel); // returns http://xxx.xxx.xxx.xxx/channel

function flush_buffers() {
    ob_end_flush();
    ob_flush();
    flush();
    //ob_start();
    fastcgi_finish_request();
}

// STREAM START
stream:
while(!connection_aborted() && user::is_enabled($username)) {
    readfile($stream);
    flush_buffers();
}
//STREAM END

sleep(10);

if(!connection_aborted()){
    goto stream;
}

user::logout($username);
exit();`

如果我理解正確,這就是您所需要的: http : //php.net/manual/en/function.connection-aborted.php

一種可能的解決方案是將腳本作為線程執行,並在后台使用exec(),shell_exec或proc_open()運行它。 這樣,您可以監視過程並輕松檢測腳本是成功退出還是被中止。 我建議使用proc_open()來輕松打開和監視管道。

這里有一些有用的鏈接處理proc_open()

http://php.net/manual/en/function.proc-open.php

http://www.molecularsciences.org/PHP/proc_open_tutorial_and_examples

http://phptutorial.info/?proc-open

我的意思是,您應該使用else語句將這些行包含在最后的if語句中,以便僅在連接中斷時注銷用戶。

if(!connection_aborted())
   {
    goto stream;
   }
else
    user::logout($username);
    exit();`
   }

如果您知道要流式傳輸的內容的文件大小,則可以在將字節數傳輸給用戶之后斷開連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM