Php - 将流复制到自身

标签 php stream

我想对 php://input 流执行操作,但也返回它。

例如,我想要实现的是:

php://input ==> 操作 ==> 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);

最佳答案

如果您对 filter 支持的操作之一感到满意在 php 中,您可以使用 php://filter fopen 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();

关于Php - 将流复制到自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23009383/

相关文章:

php - 如何获取本地服务器的时区?

php - 以下哪种方法可以提供最快的页面加载速度?

c++ - 为什么 basic_streambuf::pubseekoff() 不是纯虚函数?

java - 非缓冲 StreamReader?

python - 如何在 python 脚本中调试 KCL(python)?

c - 如何在这里使用 fscanf 从文件写入变量?

php - WordPress mysql 分组依据 |订购方式

php - 占位符的 PDO 有效字符

php - 从mysql获取所有值然后创建变量

rest - Golang channel 流