Capture user-typed input with PHP Shell

Asked

Viewed 1,313 times

11

How can I redeem input data.

Example:

> Qual seu nome?

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

> Olá, $nome-digitado

How can I do that Shell Script in PHP.

4 answers

12


I believe 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 on documentation.

  • 2

    May also be used fgets(STDIN) direct, given that the constant STDIN stores the file value php://stdin

5

You can use the function readline()

Take 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 them all with readline_list_history()

3

A simple example you can do to use is to create some functions (to do similar to goto in cmd) and use the 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

2

The question is not very clear if it is using PHP together with Shell Script (another language), or if it is using the PHP CLI (per command line), so I will cite the two cases.

Using the language Shell Script with the language PHP would be:

#!/bin/bash

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

Using the PHP CLI, to read an input line only:

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

See more in: PHP: Using the command line

  • 1

    @Guilhermenascimento, that’s right, passed blank here, thanks for the note. I’ll correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.