2014-11-08 142 views
1

我试图将文本保存到在PUT请求中发送的文件。这基本上是我使用的代码(基于documentation):stream_copy_to_stream永远不会结束

$content = fopen("php://stdin", "r"); 
    $fp = fopen($this->getFileName(), "w"); 
    stream_copy_to_stream($content, $fp); 

    fclose($fp); 
    fclose($content); 

每当我试图把东西这个脚本,它只是始终运行。使用调试器,我发现问题在stream_copy_to_stream - 脚本运行良好,但从未到达关闭资源的线路。

我在这里做错了什么?

回答

3

这是因为标准输入流不会关闭,第三个参数为stream_copy_to_stram,默认设置为读取无限数量的字节。

<?php 
$reader = fopen("php://stdin", "r"); 
$writer = fopen("test.out", "w"); 
stream_copy_to_stream($reader, $writer); 

fclose($reader); 
fclose($writer); 

尝试从命令行运行此命令。

// at this point it will block forever waiting on stdin 
$ php reader_writer.php 
Type something 
^C 

字符串“Type Something”将写入文件。在PHP 5.6 php://input is reusable

或者当

$reader = fopen("php://input", "r"); 
$writer = fopen("test.out", "w"); 
while ($line = fgets($reader)) { 
    fwrite($writer, $line, strlen($line)); 
} 

fclose($reader); 
fclose($writer); 

作为一个有趣的方面说明在命令行上:

为了解决这个问题,你可以重写。

$reader = fopen("php://stdin", "r"); 
$writer = fopen("test.out", "w"); 
while ($line = fgets($reader)) { 
    fwrite($writer, $line, strlen($line)); 
} 
fclose($reader); 
fclose($writer); 

然后运行

$ echo "sdfsdaf" | php read_write.php 
+0

你说得对!它在文档中说'php:// input',而不是'php:// stdin',因为我用... – 2014-11-08 14:54:49

相关问题