Search code examples
phpputfread

Unable to read less than 1024 bytes (1KB) with fread in PHP


I want to read a file in PUT request. As suggested in the PHP documentation:

<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>

But when the file sent is less than 1 KB, then it doesnt read. Do anyone know about this specific behaviour of fread in PHP? Thanks!

Even when the while condition is changed to while($data=fread($putdata, 512)), it doesn't go inside the loop. I don't know its specific behaviour, but is it like that fread doesn't support a chunk less than 1024? Just curious!


Solution

  • stream_get_contents($fp) worked! It returned the contents of an already open stream ($fp in this case) as a string in one shot. Thank you all for your suggestions :)