为了账号安全,请及时绑定邮箱和手机立即绑定

php detect connection status

标签:
PHP

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.

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消