Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP cli getting input from user and then dumping into variable possible?

Tags:

php

Is it possible to get input from a user using php cli and then dump the input into a variable and then the script goes ahead.

Just like the c++ cin function ?

Is that possible if yes then how ? Maybe not only php but maybe with some linux commands ?

like image 608
kritya Avatar asked Jul 01 '11 05:07

kritya


People also ask

Can we take input from user in PHP?

To get input from users, you also have to prompt them to enter something. You can use PHP's `readline() function to get this input from the console.

How do I pass a command line argument in PHP?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.

How do I prompt a user in PHP?

Solution #1: Prompt for get input inside of anywhere code: php echo "What do you want to input? "; $input = rtrim(fgets(STDIN)); echo "I got it:\n" .


2 Answers

You can simply do:

$line = fgets(STDIN); 

to read a line from standard input in php CLI mode.

like image 120
anubhava Avatar answered Oct 17 '22 05:10

anubhava


Have a look at this PHP manual page http://php.net/manual/en/features.commandline.php

in particular

<?php echo "Are you sure you want to do this?  Type 'yes' to continue: "; $handle = fopen ("php://stdin","r"); $line = fgets($handle); if(trim($line) != 'yes'){     echo "ABORTING!\n";     exit; } echo "\n"; echo "Thank you, continuing...\n"; ?> 
like image 26
Devraj Avatar answered Oct 17 '22 05:10

Devraj