PHP Standard input and loops on the command line

Getting input from standard in (STDIN) is fairly simple. There are two really easy ways: fgets() and fgetc(), for a string and character, respectively.

Usage of the two is straight-forward. Both take a resource as the first argument, in our case that resource will be STDIN. Let’s try that, shall we?

/* Start with a string */
print 'A string: ';
$astring = fgets(STDIN);
print 'A typed string: '.$astring."\n";
/* Now a Character */
print 'A character: ';
$achar = fgetc(STDIN);
print 'A typed character: '.$achar."\n";
/* Exit cleanly */

So there it is, getting input from the user of your program.
Now let’s look at the same functionality, in a looping sense. Type q to exit, or use CTRL+C.

while(!$exit) {
        /* clear the screen, using execution operators (backticks) */
        print `clear`;
        /* Request input */
        print 'Type something: ';
        /* Use fgets with the STDIN resource, and throw it in a variable */
        $var = trim(fgets(STDIN));
        /* break if it's q, otherwise keep going
           Redundant exit strategies, make $exit == 1,
                    and thus !$exit is no longer true.
           And break; explicitly tells the while() to 
                        end without going any further. */
        if ($var == 'q') {$exit++; break;}
        /* print the response */
        print 'You typed: '.$var."\n";
        /* require at least a press of enter to continue */
print 'Bye'."\n";
print `sleep 2s;clear`;

So, there it is! Getting input from standard in (STDIN) with PHP, and using the STDIN in a loop. Also, these functions are great friends with trim(), sanitizing user input is a very important step when dealing with security in your programs. You could even go one step further, and use regular expressions to ensure the type of data coming in, and ensure it’s what you want and need. Hope this was helpful!

Author: Mike on May 8, 2013
Category: PHP, Tutorials

Comments are closed.

Last articles