How to take input from command line/ STDIN in php?

There are times when a program needs to interact with user from command line or Standard Input (STDIN) / output (STDOUT). As we have learned how to use PHP from command line in previous post, This post will focus on how to read and write on Standard Input Output using PHP.

There is a concept of Streams and wrappers in PHP, as a way to handle network, data and other operations. PHP provides a number of miscellaneous I/O streams that allow access to PHP’s own input and output streams, the standard input and output. For accessing and handling various I/O streams, there is a wrapper php://. So for Standard input output STDIN/STDOUT, streams are php://stdin, php://stdout. To know more about Streams, please have a look.

Note: php://stdin is read-only, whereas php://stdout is write-only.

PHP also provides constants STDIN, STDOUT for these streams, so that we can use them directly instead of opening the streams manually. Using constants are recommended way.

Now Lets see how to use these file streams in real PHP code:

We are going to create a Greet program that will take user’s name from STDIN and will Greet him on STDOUT.

Create a php file called, greet.php having the code below:


#!/usr/bin/env php
<?php

/**
 * codezuzu
 */

echo "Dear Guest, Please Enter your name : \n";

while (true) {
    // Read the STDIN File Stream
    // This will wait for user to enter his name on command line
    $guest_name = fgets(STDIN);

    // Put bare minimum validations. Name should be atleast of 3 characters
    if (strlen(trim($guest_name)) >= 3) {

        // Remove any whitespaces or new line characters from end.
        $guest_name = rtrim($guest_name);

        // Greet the Guest
        fputs(STDOUT, "Welcome $guest_name !! \n");
        break;
    }
    
    fputs(STDOUT, "Are you sure, you don't have any name. Please Enter your name again : \n");
}


And now execute the greet.php


[nerd@codezuzu:~] # php greet.php

Dear Guest, Please Enter your name : 

# Don't enter anything, just press enter
Are you sure, you don't have any name. Please Enter your name again : 

# Don't enter anything, just press enter
Are you sure, you don't have any name. Please Enter your name again : 
        
# Don't enter anything, just press enter
Are you sure, you don't have any name. Please Enter your name again : 

# Enter "Mukesh";
Mukesh

Welcome Mukesh !! 

Bingooo!!!

So we have successfully learned, how to interact with user from command line. In further posts we will see how to use other PHP streams as well. Till then, Happy Coding !!.

Leave a Reply

Your email address will not be published. Required fields are marked *