Capture user-entered input with PHP Shell

11

How can I get you to retrieve input data.

Example:

> Qual seu nome?

...Usuário digita o seu nome...

> Olá, $nome-digitado

How can I do this via Shell Script in PHP .

    
asked by anonymous 02.01.2017 / 02:12

4 answers

13

I believe that what you want is:

<?php
echo "Qual seu nome?";
$stdin = fopen ("php://stdin","r");
$nome = fgets($stdin);
echo "Olá,", $nome, "!";
?>

For more complex entries you can use the fscanf function. More information can be found in the documentation .

    
02.01.2017 / 02:22
6

You can use the readline ()

See the example;

$nome = readline("Qual o seu nome?: ");

You can also add the input data to have a complete list with readline_add_history($sua_variavel); and then see all of them with readline_list_history()

    
02.01.2017 / 02:24
4

A simple example you can do to use is to create some functions (to do similar to goto in cmd) and use STDIN (which is a shortcut to fopen('php://stdin', 'r') ) getting something like this:

<?php
//Se a pessoa digitar "foo" chama esta função
function foo() {
    echo 'Foo', PHP_EOL;
    Pergunta();
}

//Se a pessoa digitar "sair" chama esta função
function sair() {
    exit;
}

function Pergunta() {
    echo 'O que deseja fazer?', PHP_EOL;

    $comando = trim(fgets(STDIN)); //Pega o que o usuário digitou

    if (empty($comando) === false && is_callable($comando)) {
        $comando();
    } else {
        echo 'Comando não existe', PHP_EOL;
        Pergunta(); //Se a função não existir pergunta novamente
    }
}

Pergunta(); //Inicia a função
    
02.01.2017 / 02:50
3

The question is not very clear, whether it is using PHP along with Shell Script (another language), or if it is using PHP CLI (per command line), so I'll cite both cases.

Using language Shell Script with language PHP would be:

#!/bin/bash

echo "Digite seu nome"
read nome
echo "Olá, " . $nome

Using PHP CLI , to read a single entry line:

<?php
$line = trim(fgets(STDIN)); // Recebe uma linha da entrada
fscanf(STDIN, "%d\n", $number); // Recebe número dado na entrada
?>

See more at: PHP: Using the command line

    
02.01.2017 / 02:23