Voidnull
Voidnull

Reputation: 41

PHP get more then one argument in command line

On php command line i can read only the first argument. When i add the site name the program not breaking before the password input.

echo "Site name: ";
$handle = fopen ("php://stdin","r");
$base_name = trim(fgets($handle));
fclose($handle);

echo "Password:";
$handle = fopen ("php://stdin","r");
$base_password = trim(fgets($handle));
fclose($handle);

How can i read these two variables from stdin?

Upvotes: 4

Views: 341

Answers (2)

donatJ
donatJ

Reputation: 3364

Your arguments passed at command time will be in the global $argv as well as the super global $_SERVER["argv"] with $argv[0] and $_SERVER["argv"][0] being the command that was called.

A useful function for parsing out for example the call ./myscript.php --user=root --password=foobar

function parse_argvs(){
    if( $params = $_SERVER["argv"] ){
        $file = array_shift( $params );
        while( $params ){
            $param = array_shift( $params );
            switch( strspn( $param, "-" ) ){
                case( 1 ):
                    $OPTS[ trim( $param, " -" ) ] = array_shift( $params );
                break;
                case( 2 ):
                    list( $key, $value ) = explode( "=", $param );
                    $OPTS[ trim( $key, " -" ) ] = $value;
                break;
                default:
                    $OPTS[ $param ] = true;
                break;
            }
        }
    }
    return $OPTS ?: array();
}

Called something like

$parsed = parse_argvs();
echo $parsed['user']; //root
echo $parsed['password']; //password

These are actual command line arguments passed at call time. I hope this helps.

Upvotes: 1

keithhatfield
keithhatfield

Reputation: 3273

Try this:

$base_name     = readline("Site Name: ");
$base_password = readline("Password: ");

PHP Readline Function

Upvotes: 0

Related Questions