Php readline что это

Php readline что это

The CLI SAPI defines a few constants for I/O streams to make programming for the command line a bit easier.

An already opened stream to stdin . This saves opening it with

$line = trim ( fgets ( STDIN )); // reads one line from STDIN
fscanf ( STDIN , «%d\n» , $number ); // reads number from STDIN
?>

An already opened stream to stdout . This saves opening it with

An already opened stream to stderr . This saves opening it with

Given the above, you don’t need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:

php -r 'fwrite(STDERR, "stderr\n");'

You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.

Note:

These constants are not available if reading the PHP script from stdin .

User Contributed Notes 5 notes

Please remember in multi-process applications (which are best suited under CLI), that I/O operations often will BLOCK signals from being processed.

For instance, if you have a parent waiting on fread(STDIN), it won’t handle SIGCHLD, even if you defined a signal handler for it, until after the call to fread has returned.

Your solution in this case is to wait on stream_select() to find out whether reading will block. Waiting on stream_select(), critically, does NOT BLOCK signals from being processed.

Under Linux CLI — STDIN, STDOUT and STDERR can be closed and reconnected to a different php stream such as a file, pipe or even a UDP socket_stream. (I use this technique to send the output/errors of my long running background scripts to a file so I can debug if something goes wrong.)

For example: (The below creates/appends file «/tmp/php_stdout.txt»)
// This only works under CLI in Linux
// Note: Until we have closed it STDOUT will NOT be prefixed with a $

// Get the path to the current console for STDOUT so we can reconnect later!
$strOldSTDOUT =( posix_ttyname ( STDOUT ));

echo( «This will go to the current console\r\n» );
// Close the STDOUT resource
fclose ( STDOUT );

// Reopen $STDOUT as a file Note: All further $STDOUT usage will be prefixed with a $
$STDOUT = fopen ( «/tmp/php_stdout.txt» , «a» ); /
echo( «This should append the file /tmp/php_stdout.txt\r\n» );
// Close stdout again so we can reconnect the console. Note: We are still using
fclose ( $STDOUT );

// Use the path to the console we got earlier
$STDOUT = fopen ( $strOldSTDOUT , «r+» );
echo( «And we are back on the console\r\n» );

Читайте также:  Числа фибоначчи python поиск

The command line interface data in STDIN is not made available until return is pressed.
By adding «readline_callback_handler_install(», function()<>);» before reading STDIN for the first time single key presses can be captured.

Note: This only seems to work under Linux CLI and will not work in Apache or Windows CLI.

This cam be used to obscure a password or used with ‘stream_select’ to make a non blocking keyboard monitor.

// Demo WITHOUT readline_callback_handler_install(», function()<>);
$resSTDIN = fopen ( «php://stdin» , «r» );
echo( «Type ‘x’. Then press return.» );
$strChar = stream_get_contents ( $resSTDIN , 1 );

echo( «\nYou typed: » . $strChar . «\n\n» );
fclose ( $resSTDIN );

// Demo WITH readline_callback_handler_install(», function()<>);
// This line removes the wait for on STDIN
readline_callback_handler_install ( » , function()<>);

$resSTDIN = fopen ( «php://stdin» , «r» );
echo( «We have now run: readline_callback_handler_install(», function()<>);\n» );
echo( «Press the ‘y’ key» );
$strChar = stream_get_contents ( $resSTDIN , 1 );
echo( «\nYou pressed: » . $strChar . «\nBut did not have to press \n» );
fclose ( $resSTDIN );
readline_callback_handler_remove ();
echo( «\nGoodbye\n» )
?>

It also hides text from the CLI so can be used for things like. password obscurification.
eg

readline_callback_handler_install ( » , function()<>);
echo( «Enter password followed by return. (Do not use a real one!)\n» );
echo( «Password: » );
$strObscured = » ;
while( true )
$strChar = stream_get_contents ( STDIN , 1 );
if( $strChar === chr ( 10 ))
break;
>
$strObscured .= $strChar ;
echo( «*» );
>
echo( «\n» );
echo( «You entered: » . $strObscured . «\n» );
?>

The following code shows how to test for input on STDIN. In this case, we were looking for CSV data, so we use fgetcsv to read STDIN, if it creates an array, we assume CVS input on STDIN, if no array was created, we assume there’s no input from STDIN, and look, later, to an argument with a CSV file name.

Note, without the stream_set_blocking() call, fgetcsv() hangs on STDIN, awaiting input from the user, which isn’t useful as we’re looking for a piped file. If it isn’t here already, it isn’t going to be.

stream_set_blocking ( STDIN , 0 );
$csv_ar = fgetcsv ( STDIN );
if ( is_array ( $csv_ar )) print «CVS on STDIN\n» ;
> else print «Look to ARGV for CSV file name.\n» ;
>
?>

I find a BUG with the constant STDIN, I don’t know if it si the Enter/Return key that make this proprem, when I use trim(fgets(STDIN)), that doesn’t trim anything, when I detect the length of fgets(STDIN), in windows, it is 2 characters longer than what I input, in Linux, it makes 1. I tried to trim(fgets(STDIN), ‘ \r\n’), but it still does not work.
So I have to substr the input manually, it seems like this way:
$STDIN = trim ( substr ( fgets ( STDIN ), 0 , ( PHP_OS == ‘WINNT’ ? 2 : 1 )));
?>
then I get what I want really.

Источник

Функции Readline

Readline only reads the window size on startup or on SIGWINCH. This means if the window is resized when not in a readline() call, the next call will have odd behavior due to confusion about the window size.

Читайте также:  Разделить с остатком php

The work-around is to force Readline to re-read the window size by sending it SIGWINCH. This is accomplished using the async interface, which installs the signal handler but returns control to PHP.

The following function is a drop-in replacement for readline(), but re-reads the window size every time:

function xreadline($prompt)
global $xreadline, $xreadline_line;
$code = ‘$GLOBALS[«xreadline»] = false;’ .
‘$GLOBALS[«xreadline_line»] = $line;’ .
‘readline_callback_handler_remove();’;
$cb = create_function(‘$line’, $code);
readline_callback_handler_install($prompt, $cb);
$signal = defined(«SIGWINCH») ? SIGWINCH : 28;
posix_kill(posix_getpid(), $signal);
$xreadline = true;
while ($xreadline)
readline_callback_read_char();
return is_null($xreadline_line) ? false : $xreadline_line;
>
?>

re to: ds at NOSPAM dot undesigned dot org dot za

cool program! note when trying to exec() something:
in the while loop you need to reset exec() returns or you will get all results of all executions (on my my windows and or cygwin 🙁
like:
// your class prompt()

echo «Enter something or ‘exit’ to quit\n» ;
do $cmdline = new prompt ();
$buffer = $cmdline -> get ( ‘shell command: ‘ );
// init/ reset first!
$data = null ;
$return = null ;
// now start:
echo «You said: $buffer \n» ;
if (!empty( $buffer )) $x = exec ( $buffer , $data , $return );
print_r ( $data );
>
> while ( $buffer !== «exit» );
echo «Goodbye\n» ;

Windows.
To the current date, PHP 8.1 64bits under Windows does not support all the functions:

supported:
readline_add_history
readline_clear_history
readline_completion_function
readline_info
readline_list_history
readline_read_history
readline_write_history
readline

no supported: (the function is not even defined)

if you want to read a key in windows (without blocking), you can use the next code:

$out=»;
$ret=»;
$keys=’1234567890abcdefghijklmnopqrstuvwxyz’.»á»;
$default=»á»;
while(true) exec(«choice /N /C $keys /D $default /T 1»,$out,$ret);
if($out[0]!==»á») var_dump($out[0]);
>
$out=[];
>

It is not elegant and it calls choice every 1 second but it does the job (at least with some keys).

There is a simpler way to do a multiline read than above:

function multiline() while(($in = readline(«»)) != «.»)
$story .= ($PHP_OS == «WINNT») ? «\r\n».$in :
«\n».$in;

Here’s an example simple readline-like way to input from command line on windows — the single line is from http://www.phpbuilder.com/columns/darrell20000319.php3, the multiline is something I added.

function read () # 4092 max on win32 fopen

$fp=fopen(«php://stdin», «r»);
$in=fgets($fp,4094);
fclose($fp);

# strip newline
(PHP_OS == «WINNT») ? ($read = str_replace(«\r\n», «», $in)) : ($read = str_replace(«\n», «», $in));

function multilineread () do $in = read();

# test exit
if ($in == «.») return $read;

# concat input
(PHP_OS == «WINNT») ? ($read = $read . ($read ? «\r\n» : «») . $in) : ($read = $read . «\n» . $in);

print(«End input with . on line by itself.\n»);

print(«What is your first name?\n»);
$first_name = multilineread();

print(«What is your last name?\n»);
$last_name = read();

print(«\nHello, $first_name $last_name! Nice to meet you! \n»);
?>

Источник

How to read a user’s input to the PHP console

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

What is a PHP console?

A PHP console is a command-line interface for writing and executing PHP codes. A PHP console is usually called the PHP interactive shell.

If you have PHP installed, you can access the console with the terminal command below:

Читайте также:  Select query database java

However, it is more difficult to get user input through the PHP console as compared to using web browsers for input.

Prompting users for input

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.

What is the readline() function?

readline() is a built-in function in PHP that enables us to read input from the console. The function accepts an optional parameter that contains text to display.

Syntax

Code

The code below shows how you can read a single input from the user.

// Input section
// get users name
$name = (string)readline("Your name: ")
$int = (int)readline('Enter an integer: ');
$float = (float)readline('Enter a floating'
. ' point number: ');
// Entered integer is 10 and
// entered float is 9.78
echo "Hello ".$name." The integer value you entered is "
. $int
. " and the float value is " . $float;
?>

The result of executing the script above is as follows:

As the code executes, you can see how the readline() function sends prompts to the console in order to take inputs.

Remember that to successfully execute this script on the command line, you must have added PHP to your system environment path.

Accepting multiple inputs

The readline() function can also help you accept multiple inputs, which are separated by some delimiter.

To achieve this, you must use another function called explode() together with readline() . The first argument of explode() is the delimiter you want to use. The second argument will be the readline() function.

The code below shows how to accept multiple inputs from the console:

Источник

Php readline что это

readline()-это встроенная функция в PHP,которая позволяет нам читать ввод с консоли.Функция принимает необязательный параметр,содержащий текст для отображения.

Можем ли мы принимать ввод от пользователя в PHP?

Способ 1:Использование функции readline()-это встроенная функция в PHP.Эта функция используется для чтения ввода с консоли.

Что такое Stdin PHP?

Стандартные потоки php://stdin,php://stdout и php://stderr обеспечивают прямой доступ к устройству стандартного входного потока,стандартного выходного потока и потока ошибок для процесса PHP соответственно.Предопределенные константы STDIN,STDOUT и STDERR соответственно представляют эти потоки.

Что такое функция readline ()?

Функция readline()считывает строку файла и возвращает ее в виде строки.Она принимает параметр n,который задает максимальное количество байт,которые будут прочитаны.

Для чего используется метод readline ()?

Безопасен ли ввод данных PHP?

Если вы сделаете что-то вроде exec(php://input) (psuedocode), у вас будет плохой день. Если вместо этого вы просто читаете входной поток и правильно обрабатываете полученные данные, все в порядке. Во входном потоке нет ничего безопасного или небезопасного. Важно то, что вы с ним делаете.

Что такое $_GET и $_POST в PHP?

$_GET-это массив переменных,переданных текущему скрипту через параметры URL.$_POST-это массив переменных,переданных текущему скрипту через метод HTTP POST.

Источник

Оцените статью