2011-02-18 51 views
1

退出如何暫停命令行腳本的執行,以給用戶提供了一個按Ctrl +Ç退出它的可能性?暫停PHP CLI腳本給用戶可能用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()); 
} 

?> 

使用的CentOS Linux的5.5 + PHP 5.1.6 + PostgreSQL 8.4.7。

回答

8

試一下:

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

    echo "OK!"; 
2

sleep(5);將等待5秒鐘。

如果你想要更多的東西花哨:

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

如果你不想睡覺,但喜歡是/否式提示:

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

不,謝謝,不想在這裏用睡覺 – 2011-02-18 12:29:47

+0

感謝您回覆並擴大您的答案。雖然我會和弗朗切斯科的回答一起去,因爲不想依賴readline – 2011-02-18 12:41:24