2014-04-11 22 views
2

我想對php://input流執行操作,但也返回它。Php - 將流複製到自身

例如,我想實現的是:

php://input ==> OPERATION ==> php://input

這有可能做出這樣的事情?

$input = fopen("php://input", "r"); 
$output = fopen("php://input", "w"); 
while (($buffer.= fgets($input, 1024)) !== false) { 
    // Do something with that buffer 
    // ?? 
    fwrite($output, $buffer); 

} 
fclose($output); 
fclose($input); 

回答

2

如果你是支持作爲PHP中的filter的某個操作精細,你可以使用php://filterfopen wrapper

比方說,你要爲Base64解碼的數據。例如:

$data = file_get_contents('php://filter/read=convert.base64-decode/resource=php://input'); 

或者:

$input = fopen('php://filter/read=convert.base64-decode/resource=php://input'); 
// now you can pass $input to somewhere and every read operation will 
// return base64 decoded data ... 

然而,支持在PHP中的過濾器設置的操作是相當有限。如果它不適合你的需要,我會建議將文件指針包裝在一個類中。又來了一個非常簡單的例子,你可以添加緩存,緩存或任何...

class Input { 

    public static function read() { 
     return $this->process(file_get_contents('php://stdin')); 
    } 


    public function process($data) { 
     return do_whatever_with($data); 
    } 

} 

然後在應用程序代碼中使用:

$input = Input::read(); 
+0

謝謝您的回答,但通過'客戶operation'我的意思,添加或刪除內容。這比b64編碼/解碼更復雜一些。 – Manitoba

+0

啊。你的問題有點不清楚,所以我認爲這可能是有趣的。不幸的是,這套可用的過濾器非常有限。讓我試着給出一個替代方案... – hek2mgl

+0

感謝您的幫助;) – Manitoba