php detect connection status

來源:互聯網
上載者:User

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.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.