PHP I / O redirection

<?php
    fclose(STDIN);
    fclose(STDOUT);
    fclose(STDERR);

    $STDIN = fopen("/tmp/some-named-pipe", "r");
    $STDOUT = fopen("/tmp/foo.out", "wb");
    $STDERR = fopen("/tmp/foo.err", "wb");

    echo "Hello, World!";                 // goes to /tmp/foo.out, implied STDOUT
    fscanf($STDIN, "%s\n", $top_secret);  // explicit $STDIN, cant use STDIN
?>

Why does redirecting to the new STDOUT work implicitly, but should redirection from the new STDIN be explicit?

+2
source share
4 answers

The original STDIN, STDOUT, and STDERR are system constants in PHP. They are populated with file descriptors for standard input, output, and PHP initialization errors.

The php.net documentation describes the following resources in constants:

Value of a constant; only scalar and zero values ​​are allowed. Scalar values ​​are integer, float, string, or boolean. it is possible to define resource constants, however this is not recommended and may cause unpredictable behavior.

fclose(STDOUT), STDOUT. STDOUT .

echo' echo "Hello, World!", PHP STDOUT, . , STDOUT , fclose'd. fwrite(STDOUT, "hello") .

, $STDOUT. , , . PHP, STDOUT . STDOUT.

, , PHP , , " " , .

+5

stdout . STDOUT , $STDOUT.

<?php
# Redirecting 10 times ...
# Need to close 'STDOUT' & '$STDOUT', otherwise the 2nd time
# the redirecting fails.

for ( $i = 1; $i <= 10; $i++ )
{
  $sLogName = sprintf("reopen_%02d.log", $i);
  echo "Redirecting to '" . $sLogName . "' ...\n";

  fclose(STDOUT);
  fclose($STDOUT);  # Needed for reopening after the first time.

  $STDOUT = fopen($sLogName, "w");
  echo "Now logging in file '" . $sLogName . "' ...\n";
}
?>
+2

UNIX- (linux ..), unix, , STDIN, STDOUT STDERR 0,1 2. :

fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);

$STDIN = fopen("/tmp/some-named-pipe", "r");
$STDOUT = fopen("/tmp/foo.out", "wb");
$STDERR = fopen("/tmp/foo.err", "wb");

STDIN (0), STDOUT (1) STDERR (2), , , 0,1 2 . , .

+1

The first thing I see when reading your fragment is that you first try to close the constants STDIN, STDOUT, etc. But then use variables that have the same name to open files; therefore, the values ​​you work with are completely different, $ STDIN is not the same as STDIN. You may be able to override STDIN with the define function, but I'm not sure and cannot check without an atm computer.

0
source

All Articles