继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

php detect connection status

ajax快速入门培训基础
关注TA
已关注
手记 284
粉丝 176
获赞 719

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.

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP