doujiao7325 2011-02-18 12:24
浏览 114
已采纳

暂停PHP CLI脚本以使用户可以使用CTRL-C退出

How to pause the execution of a command line script to give the user the possibility to exit it with a <kbd>Ctrl</kbd>+<kbd>C</kbd>?

For example I have this script for deleting a user id from a number of tables, but would like to halt the script before really doing it:

<?php

define('DBHOST', '/tmp');
define('DBNAME', 'XXX');
define('DBUSER', 'YYY');
define('DBPASS', 'ZZZ');

$TABLES = array('pref_game',
                'pref_hand',
                'pref_luck',
                'pref_match',
                'pref_misere',
                'pref_money',
                'pref_pass',
                'pref_rep',
                'pref_status',
                'pref_users'
        );

if ($argc != 2)
        exit("Missing user id
");

if (!preg_match('/^([A-Z]{2}[0-9]+)$/', $argv[1], $matches))
        exit("Invalid user id
");

$id = $matches[1];
printf("Deleting user %s Press CTRL-C to abort

", $id);

# XXX stop here, but how? XXX

try {
        $db = new PDO('pgsql:host=' . DBHOST . '; dbname=' . DBNAME, DBUSER, DBPASS);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        foreach ($TABLES as $table) {
                $sql = sprintf('delete from %s where id=?', $table);
                run_sql($db, $sql, $id);
        }

} catch (Exception $e) {
       exit('Database problem: ' . $e->getMessage());
}

function run_sql($db, $sql, $arg) {
        $sth = $db->prepare($sql);
        $sth->execute(array($arg));
        printf("SQL: %s
Affected rows: %d

", $sql, $sth->rowCount());
}

?>

Using CentOS Linux 5.5 + PHP 5.1.6 + PostgreSQL 8.4.7.

  • 写回答

3条回答 默认 最新

  • dpleylxzx47207117 2011-02-18 12:28
    关注

    Try with:

        printf("Deleting user %s Press CTRL-C to abort, enter to continue
    
    ", $id);
        $fp = fopen("php://stdin","r");
        fgets($fp);
    
        echo "OK!";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真