1

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

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\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());
}

?>

Using CentOS Linux 5.5 + PHP 5.1.6 + PostgreSQL 8.4.7.

3 Answers 3

10

Try with:

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

    echo "OK!";
Sign up to request clarification or add additional context in comments.

Comments

2

sleep(5); would wait for five seconds.

If you want something more fancy:

function delay($duration) {
    while($duration) {
        echo "\rStarting in ".$duration--.'...';
        sleep(1);
    }
    echo "\n";
}

If you don't want to sleep but prefer a yes/no-style prompt:

function confirm($question) {
    while(true) {
        $line = strtolower(trim(readline($question.'? [Y/n]')));
        if(!$line || $line == 'y') {
            return true;
        }
        elseif($line == 'n') {
            return false;
        }
    }
}

1 Comment

Thanks for returning back and expanding your answer. I'll go with Francesco's answer though, because do not want to depend on readline
0

Use sleep() or read from stdin until you get a newline: http://php.net/manual/en/wrappers.php.php

1 Comment

Thanks, but do you have a 1-2 lines solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.