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

Ale*_*ber 1 php command-line command-line-interface

如何暂停执行命令行脚本以使用户可以使用Ctrl+ C

例如,我有这个脚本用于从许多表中删除用户ID,但是想要在真正执行之前暂停脚本:

<?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\n");

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

$id = $matches[1];
printf("Deleting user %s Press CTRL-C to abort\n\n", $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\nAffected rows: %d\n\n", $sql, $sth->rowCount());
}

?>
Run Code Online (Sandbox Code Playgroud)

使用CentOS Linux 5.5 + PHP 5.1.6 + PostgreSQL 8.4.7.

Fra*_*ita 10

试试:

    printf("Deleting user %s Press CTRL-C to abort, enter to continue\n\n", $id);
    $fp = fopen("php://stdin","r");
    fgets($fp);

    echo "OK!";
Run Code Online (Sandbox Code Playgroud)