PHP: Output Error Messages to Standard Error Stream

Sometimes we will come to situations where we want to print error messages directly to stderr (Standard Error stream). Most probably when we are writing CLI applications. Users can direct program output to a text file but we need to show the error messages always in terminal.

We can open stderr as file and write to it to achieve our goal.

$stderr = fopen('php://stderr', 'w+');
fwrite($stderr, "Error message");

We may create a function wrapping this and call it as needed.

function print_error($message) {
  static $stderr;
  if (!isset($stderr)) {
    $stderr = fopen('php://stderr', 'w+');
  }
  fwrite($stderr, $message);
}

There is built in function error_log() that can be used to print error messages. But it will send messages to system log or a file depending on settings in php.ini.