Alternative way to read raw I/O stream in PHP

2020-07-18 05:56发布

问题:

I am trying to find an alternative to reading php://input. I use this for getting XML data from a CURL PUT.

I usually do this with:

$xml = file_get_contents('php://input');

However, I'm having a few issues with file_get_contents() on Windows.

Is there an alternative, perhaps using fopen() or fread()?

回答1:

Yes, you can do:

$f = fopen('php://input', 'r');
if (!$f)  die("Couldn't open input stream\n");
$data = '';
while ($buffer =  fread($f, 8192)) $data .= $buffer;
fclose($f);

But, the question you have to ask yourself is why isn't file_get_contents working on windows? Because if it's not working, I doubt fopen would work for the same stream...



回答2:

Ok. I think I've found a solution.

$f = @fopen("php://input", "r");
$file_data_str = stream_get_contents($f);
fclose($f);

Plus, with this, I'm not mandated to put in a file size.



标签: php file-io io