Last Updated: February 25, 2016
·
1.214K
· mtthlm

How to capture user input using STDIN in PHP CLI

If you're writing a PHP CLI script, this will come in handy. Interested in knowing how to capture user input to ask a question, or record data? Check this out:

<?php

// OPENING LINE BREAK
print PHP_EOL;

// ASK QUESTION
print 'What is your birthday? (mm/dd/yyyy) ';

// OPEN STDIN HANDLE
$stdin = fopen( 'php://stdin' , 'r' );

// GET ANSWER
$answer = fgets( $stdin );

// CLOSE STDIN HANDLE
fclose( $stdin );

// TRIM ANSWER (LINE BREAKS, WHITESPACE, ETC.)
$birthday = trim( $answer );

// CALCULATE AGE USING DATETIME CLASS
$age = DateTime::createFromFormat( 'm/d/Y' , $birthday )->diff( new DateTime( 'now' ) )->y;

// LINE BREAK FOR SPACING
print PHP_EOL;

// PRINT AGE
print 'You are ' . $age . ' years old.' . PHP_EOL;

// CLOSING LINE BREAK
print PHP_EOL;