Standard input code php

PHP standard input?

One alternative approach could be to employ multiple regex statements to verify whether the string resembles a double, a boolean, an integer, and so on. In this scenario, you can employ the «\d+» pattern to validate if the input only contains digits.

PHP standard input?

Although PHP is mainly used for web development where standard input may not be required, it claims to be usable as a general-purpose language if you follow its web-based conventions. PHP allows output to be printed to a designated location, which is straightforward. However, I’m curious about how a PHP script can receive input from a specific source using a particular input function. Is this even feasible, or am I mistaken?

By establishing a connection between stdin and php://stdin , it becomes feasible to access the former. fgets() can be used to read a line, while fgetc() is capable of reading a single character, as previously mentioned.

The preferred method is to read input from the standard input stream (STDIN).

Utilize file_get_contents() and php://stdin to circumvent the need to manipulate filehandles.

$ echo 'Hello, World!' | php -r 'echo file_get_contents("php://stdin");' Hello, World! 

In case you need to read an extensive amount of data from stdin , it may be necessary to use the filehandle approach. However, for several megabytes, the current approach should suffice.

Читайте также:  Java firefox всегда включать

Read stdin line by line, I need to read stdin with php. I need to read first line > save it to the variable > print this variable > read second line > save it to

How can I find the PHP STDIN input data type

My name is reading input and I am looking to determine the data type of the provided input through STDIN.

Can anyone please give any idea?

To obtain the type, you will need to perform a manual check.

if (is_int($mystr)) < return 'int'; >if (is_bool($mystr) < return 'bool'; >if (is_string($mystr))

Another option is to convert the $mystr to an integer using $mystr = (int) $mystr , which will enable you to obtain the gettype($mystr) .

To verify if the data is JSON, an alternative approach is to unserialise it and search for any problems. If there are issues, it is highly unlikely to be JSON. Otherwise, returning the string is a viable fallback option.

You possess several checks of types, such as:

  • is_array
  • is_bool
  • is_int
  • is_string
  • is_object
  • is_callable

For your case, you will only require the 3/4 from the given list through STDIN.

Utilizing the Ctype library enables you to verify the content of your string. To confirm that the input comprises solely of numbers, you may apply ctype_digit() .

An alternative approach could involve utilizing multiple regex statements to verify whether the given string conforms to any of the following data types: double, boolean, integer, and so on.

Php — Simple way to read variables on different lines from STDIN?, The same code is obviously usable with input redirection, so you can feed a file into the script which makes detaching the standard input

Read STDIN line by line in PHP

I want to do something like this:

1,abc,100 2,xyz,200 3,uyx,300 4,sje,400 5,tek,500 

When I send this input to PHP, it only reads the initial line before abruptly closing the stream. My goal is to keep the stream open at all times and read/write all lines, similar to using a stream with a timeout.

My code snippet is as follows:

setLogLevel(LOG_DEBUG); $rk->addBrokers("localhost:9092"); $topic = $rk->newTopic("testing"); $temp = fopen("php://stdin","r"); $line = fgets($temp); $foo = rtrim($line); $topic->produce(RD_KAFKA_PARTITION_UA,0,$foo); 

The function performs as intended, producing a single output for the given fgets() . This is in accordance with the documentation.

The reading process stops when either the number of bytes read equals length — 1, or the first occurrence of a newline (which is also returned), or an EOF, whichever comes first.

In order to access additional content, you must engage in a looping process.

while (!feof($temp)) < $line = rtrim(fgets($temp)); $topic->produce(RD_KAFKA_PARTITION_UA, 0, $line); > 

Reading line by line from STDIN, In parse_STDIN.php file I want to be able to parse my data line by line from stdin. Have you tried calling that query from within the PHP

Источник

Standard input code php

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» );

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.

Источник

PHP Standard Input

It is possible to read the stdin by creating a file handle to php://stdin and then read from it with fgets() for a line for example (or, as you already stated, fgetc() for a single character):

$f = fopen( 'php://stdin', 'r' );

while( $line = fgets( $f ) ) echo $line;
>

fclose( $f );
?>

Reading line by line from STDIN

use STDIN constant as file handler.

while($f = fgets(STDIN)) echo "line: $f";
>

Note: fgets on STDIN reads the \n character.

redirect a file contents to standard input in php

How to process stdin to stdout in php?

If you are piping, you will want to buffer the input, instead of processing it all at once, just go one line at a time as is standard for *nix tools.

The SheBang on top of the file allows you to execute the file directly, instead of having to call php in the command line.

Save the following to test.php and run

#!php
$handle = fopen('php://stdin', 'r');
$count = 0;
while(!feof($handle)) $buffer = fgets($handle);
echo $count++, ": ", $buffer;
>
fclose($handle);

How to take multiple standard input in a single line using php command line

Actually, the problem is in the following line:

$myPosition = (int) fgets(STDIN);

Here, the explicit conversion to int is discarding the value after space, so when you give 1 2 as the input in the command line the (int) is turning it into 1 and you are losing the other character.

$arr = [];
$testCase = (int) fgets(STDIN);

while ($testCase--) list($a, $b) = explode(' ', fgets(STDIN));
$arr[] = $a.' '.$b;
>

print_r($arr);

The above solution works because I’ve removed the (int) from the beginning of the fgets . Also note that, I’m using list($a, $b) here, which will actually create two variable $a and $b in the current scope so I’m always assuming that, you’ll use two separate numbers (i.e: 1 2), otherwise you can use $inputParts = preg_split(«/[\s]+/»,$input) or something else with explode to form the array from input from console.

How to use STDOUT in php

Okay, let me give you another example for the STDIN and STDOUT usage.

In PHP you use these two idioms:

 $input = fgets(STDIN);

fwrite(STDOUT, $output);

When from the commandline you utilize them as such:

 cat "input.txt" | php script.php > "output.txt"

php script.php < input.txt >output.txt

echo "input. " | php script.php | sort | tee output.txt

That’s all these things do. Piping in, or piping out. And the incoming parts will appear in STDIN , whereas your output should go to STDOUT . Never cross the streams, folks!

PHP — detect STDIO input

if(FALSE !== ftell(STDIN))
while (FALSE !== ($line = fgets(STDIN)))
$customLogArr[]=$line;
>
>

For STDIN, if nothing can be read, ftell() will return false.

How can I check if stdin exists in PHP ( php-cgi )?

The problem is that you create a endless loop with the while($line = fgets($fh)) part in your code.

$stdin = '';
$fh = fopen('php://stdin','r');
if($fh) // read *one* line from stdin upto "\r\n"
$stdin = fgets($fh);
fclose($fh);
>
echo $stdin;

The above would work if you’re passing arguments like echo foo=bar | ./myscript.php and will read a single line when you call it like ./myscript.php
If you like to read more lines and keep your original code you can send a quit signal CTRL + D

To get parameters passed like ./myscript.php foo=bar you could check the contents of the $argv variable, in which the first argument always is the name of the executing script:

 ./myscript.php foo=bar

// File: myscript.php
$stdin = '';
for($i = 1; $i < count($argv); i++) $stdin .= $argv[$i];
>

I’m not sure that this solves anything but perhaps it give you some ideas.

Источник

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