6.11 Manipulating Standard I/O Streams
TechniquePHP provides access to the standard I/O streams via the php:// type of server. (It's weird, I know, but it makes it easier on the C side.) <?php $fp = @fopen("php://stdin", "r") or die("Cannot access Standard In"); //... manipulate STDIN with the different file access functions fclose($fp); ?> CommentsSTDIN , STDOUT , and STDERR are the common input, output, and error streams for most programming languages. However, PHP has traditionally been a Web-scripting language, so access to these streams is a fairly new feature with version 3.013. For the uninitiated, here is a description of each of the streams: STDIN This is standard input; this is either what you type in at the command prompt or data that is sent from a post request. STDOUT This is standard output; it is the stream for normal data output. STDERR This is standard error; this is where the error messages are usually output. You can use this if you want to log errors instead of printing them to the screen. The following is an example of using STDERR to send errors to the standard error stream: <?php include_once 'DB.php'; function log_error ($message = "error") { error_log ($message, "php://stderr", 3); } $dbh = DB::connect('mysql://sterling:secret@localhost/dbname'); if (DB::isError ($dbh)) { $errmsg = sprintf ('MySQL Error [%d]: %s', $dbh->getCode(), $dbh->getMessage()); log_error ($errmsg) && die ($errmsg); } $stmt = "SELECT * FROM tablename"; $sth = $dbh->query ($stmt); if (DB::isError ($sth)) { $errmsg = sprintf ('MySQL Error [%d]: %s', $dbh->getCode(), $dbh->getMessage()); log_error ($errmsg) && die ($errmsg); } $sth->free(); $dbh->close(); ?> |