Skip to content

Instantly share code, notes, and snippets.

@jachin
Created June 21, 2011 04:34
Show Gist options
  • Save jachin/1037249 to your computer and use it in GitHub Desktop.
Save jachin/1037249 to your computer and use it in GitHub Desktop.
PHP Command Line Confirmation Prompt
$message = "Are you sure you want to do this [y/N]";
print $message;
flush();
ob_flush();
$confirmation = trim( fgets( STDIN ) );
if ( $confirmation !== 'y' ) {
// The user did not say 'y'.
exit (0);
}
@kwm-ferhat
Copy link

Very nice, thank you for this helpful snippet.

@dimaslanjaka
Copy link

here my modification

/**
 * Prompts the user for confirmation with a message.
 *
 * @param string $message The confirmation message.
 * @return bool True if user confirms (y/yes), false otherwise (n/no).
 */
function confirmAction(string $message = "Are you sure? (y/n): "): bool
{
  $validResponses = ['y', 'yes', 'n', 'no'];
  $response = '';

  while (!in_array($response, $validResponses)) {
    echo $message;
    $response = strtolower(trim(fgets(STDIN)));
  }

  return in_array($response, ['y', 'yes']);
}

my blog

@oranfry
Copy link

oranfry commented Aug 28, 2024

And here is mine.

function confirm(?string $message = null): bool
{
    do {
        echo ltrim($message . " (y/n): ");
        $response = strtolower(trim(fgets(STDIN)));
    } while (null === $result = match ($response) {
        'y', 'yes' => true,
        'n', 'no' => false,
        default => null,
    });

    return $result;
}

@ve3
Copy link

ve3 commented Sep 16, 2024

Use exit(1) instead of exit(0) to prevent next process running.
Example command: php confirm-this.php && php run-that.php.
If enter n then run-that.php will not run because exit(1).

Also prevent no buffer to flush error with ob_get_level(). Example:

if (ob_get_level() > 0) {
    ob_flush();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment