Created
May 28, 2014 14:25
-
-
Save toddsby/989afb145632d659216c to your computer and use it in GitHub Desktop.
IOMode Class PHP STDIN && STDOUT && STDERR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class IOMode | |
{ | |
public $stdin; | |
public $stdout; | |
public $stderr; | |
private function getMode(&$dev, $fp) | |
{ | |
$stat = fstat($fp); | |
$mode = $stat['mode'] & 0170000; // S_IFMT | |
$dev = new StdClass; | |
$dev->isFifo = $mode == 0010000; // S_IFIFO | |
$dev->isChr = $mode == 0020000; // S_IFCHR | |
$dev->isDir = $mode == 0040000; // S_IFDIR | |
$dev->isBlk = $mode == 0060000; // S_IFBLK | |
$dev->isReg = $mode == 0100000; // S_IFREG | |
$dev->isLnk = $mode == 0120000; // S_IFLNK | |
$dev->isSock = $mode == 0140000; // S_IFSOCK | |
} | |
public function __construct() | |
{ | |
$this->getMode($this->stdin, STDIN); | |
$this->getMode($this->stdout, STDOUT); | |
$this->getMode($this->stderr, STDERR); | |
} | |
} | |
$io = new IOMode; |
Example usage
Input:
$ php io.php
// Character device as input
// $io->stdin->isChr == true
$ echo | php io.php
// Input piped from another command
// $io->stdin->isFifo == true
$ php io.php < infile
// Input from a regular file (name taken verbatim from C headers)
// $io->stdin->isReg == true
$ mkdir test
$ php io.php < test
// Directory used as input
// $io->stdin->isDir == true
Output:
$ php io.php
// $io->stdout->isChr == true
$ php io.php | cat
// $io->stdout->isFifo == true
$ php io.php > outfile
// $io->stdout->isReg == true
Error:
$ php io.php
// $io->stderr->isChr == true
$ php io.php 2>&1 | cat
// stderr redirected to stdout AND piped to another command
// $io->stderr->isFifo == true
$ php io.php 2>error
// $io->stderr->isReg == true
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken from http://stackoverflow.com/a/11327451