PHP 5.6.38 Released

Ein- und Ausgabestreams

Die CLI SAPI definiert einige Konstanten für Ein- und Ausgabestreams, um das Erstellen von Kommandozeilenanwendungen zu erleichtern.

CLI-spezifische Konstanten
Konstante Beschreibung
STDIN

Ein schon geöffneter Stream auf stdin. Dies erspart das Öffnen mit

<?php
$stdin 
fopen('php://stdin''r');
?>
Wenn sie einzelne Zeilen von stdin lesen wollen, können Sie folgendes Code-Fragment benutzen:
<?php
$line 
trim(fgets(STDIN)); // liest eine Zeile von STDIN
fscanf(STDIN"%d\n"$number); // liest eine Zahl von STDIN
?>

STDOUT

Ein schon geöffneter Stream auf stdout. Das erspart das Öffnen mit

<?php
$stdout 
fopen('php://stdout''w');
?>

STDERR

Ein schon geöffneter Stream auf stderr. Das erspart das Öffnen mit

<?php
$stderr 
fopen('php://stderr''w');
?>

Angesichts des oben genannten, brauchen Sie beispielsweise nicht selbst einen Stream für stderr öffnen, sondern können einfach die Konstante anstelle der Ressource benutzen:

php -r 'fwrite(STDERR, "stderr\n");'
Sie brauchen diese Streams nicht explizit schließen, weil sie automatisch von PHP geschlossen werden, wenn Ihr Skript endet.

Hinweis:

Diese Konstanten sind nicht verfügbar, wenn ein PHP Skript von stdin eingelesen wird.

add a note add a note

User Contributed Notes 5 notes

up
30
Aurelien Marchand
7 years ago
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.

Aurelien
up
10
ecrist at secure-computing dot net
7 years ago
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.

<?php
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";
}
?>
up
0
phil_php at zieaon dot com
1 month ago
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.

<?php

// 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 <CR> 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 <cr>\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

<?php
    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");
?>
up
-3
ayon at hyurl dot com
1 year ago
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:
<?php
$STDIN
= trim(substr(fgets(STDIN), 0, (PHP_OS == 'WINNT' ? 2 : 1)));
?>
then I get what I want really.
up
-56
James Zhu
7 years ago
Example:

<?php
function ReadStdin($prompt, $valid_inputs, $default = '') {
    while(!isset(
$input) || (is_array($valid_inputs) && !in_array($input, $valid_inputs)) || ($valid_inputs == 'is_file' && !is_file($input))) {
        echo
$prompt;
       
$input = strtolower(trim(fgets(STDIN)));
        if(empty(
$input) && !empty($default)) {
           
$input = $default;
        }
    }
    return
$input;
}

// you can input <Enter> or 1, 2, 3
$choice = ReadStdin('Please choose your answer or press Enter to continue: ', array('', '1', '2', '3'));

// check input is valid file name, use /var/path for input nothing
$file = ReadStdin('Please input the file name(/var/path):', 'is_file', '/var/path');
?>

you can add more functions if you want.
To Top