How to make PHP read input on command line as string?

1

In Python , I know that to read the data entered by the command line we use the function raw_input .

Example:

Python script:

print 'digite algo para inicializar'

resultado = raw_input()

print 'O resultado é ' + resultado

Command line:

> python script.py
digite algo para inicializar
> teste
o resultado é teste

What about PHP? How to make PHP read input from the command line?

Note : I want to capture the entry not at script startup, but "in the middle" of it, as in the example of python , shown above.     

asked by anonymous 31.08.2015 / 17:06

2 answers

0

This can be done through the function fgets combined with the constant STDIN .

See:

$line = fgets(STDIN);

PHP script

echo "iniciando a aplicação php\n";

$line = fgets(STDIN);

echo "O resultado é '{$line}'";

Seetheanswerfrom SOEN

While fgets is used in most cases to read file pointers, PHP supports protocol and wrapper support through these functions.

In this case, we are reading the command line entry as if it were a line in a file.

See the code working at IDEONE

    
31.08.2015 / 17:14
2

For data entry in php use "argv": $argv[0] .

Here is an example for inputting a single parameter:

<?php

if ($argc != 2 || in_array($argv[1], array('texto1', 'texto 2', 'texto3', 'texto4'))) {
     echo $argv[0]; 
} else {
     echo $argv[1];
}

 ?>

link

Here you have more details about command line: link

And here are some examples of usage: link

    
31.08.2015 / 17:21