I want to write a PHP script to be executed via CLI which will automatically deploy a code base for a new website on my workstation. I've never written a cli script that prompts a user for input and am looking for suggestions about how to repeatedly prompt a user for input until they enter a valid value (or somehow abort the script). I will probably have to prompt them six times and want to make sure they provide valid file paths, a correct email address, and possibly other things. Has anyone got a tried & true way they do this?
I found the following code in the PHP docs:
<?php
function ReadStdin($prompt, $valid_inputs, $default = '') {
while(!isset($input) || (is_array($valid_inputs) && !in_array($input, $valid_inputs)) || ($valid_inputs == 'is_file' && !is_file($input))) {
echo $prompt;
$input = strtolower(trim(fgets(STDIN)));
if(empty($input) && !empty($default)) {
$input = $default;
}
}
return $input;
}
// you can input <Enter> or 1, 2, 3
$choice = ReadStdin('Please choose your answer or press Enter to continue: ', array('', '1', '2', '3'));
// check input is valid file name, use /var/path for input nothing
$file = ReadStdin('Please input the file name(/var/path):', 'is_file', '/var/path');
?>
It looks like a good start but seems to me rather than $valid_inputs, you should provide a callback function for validation.