php detect connection status

PHP script executed terminal


  • PHP script can be possiblly terminaled in those situations:

1, Max time limiation is reaching.

2, The user hit "stop" button, and in backup server, ignore_user_abort is not setted, when user output something, the php script will stop to be executed.

3, A whole php script page has been executed.


  • Then how to detect connections has been stoped by client PHP internal.

1, do not set ingnore_user_abort to true.

2, Output something,

3, Use "register_shutdown_function" to register a function to be called when PHP script stopped to be executed.

4, Use "connection_status" to return the current connection status to determine following action.


  • Connection status has 3 options

0 - NORMAL

1 - ABORTED

2 - TIMEOUT


In comet functions, when call PHP script, there will be while loop in php script and will never been stopped if server is not returned. But at the same time, client may close the connection to server, but PHP can not detect it. If so, there will be much resource wasted in server. In my project, I connect to mysql server by persistent connection. Because no script to detect connection, when use refresh the page(Especially in development phase), a database connection will be kept, this made the system print out a error say"too many connections to mysql server". So in those application, we must have machanism to detect connection status. Code example:


if($mysql->connect_errno > 0){

$rs['status'] = false;

$rs['data'] = '鏈接數據庫失敗';

echo json_encode($rs);

exit;

}

function close($mysql=null){

if($mysql){

$mysql->close();

}

}

register_shutdown_function('close');

$mysql->query("SET NAMES 'utf8'");

while(1){

$rs = array();

$result = $mysql->query("SELECT count(0) AS cnt FROM modoer_tmp_products WHERE status = '1'");

$row = $result->fetch_assoc();

if($row['cnt'] > 0){

$rs['count'] = $row['cnt'];

$rs['status'] = true;

echo json_encode($rs);

exit;

}

else{

echo '0';

flush();

ob_flush();

sleep(1);

}

}

Please note that, in this way, client(browser) will receive some unuseful string(0). To make program work properly, the client should handle it.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章