流写无效的图像内容

I have a php script which store images from put request. The script is hosted on Host Monster

Here is my script

<?php    

$path = 'test.png';        

$put = fopen("php://input", "r");   

$fp = fopen($path, "w");    

while ($data = fread($put, 1024))
    fwrite($fp, $data);     

fclose($fp);
fclose($put);

echo 'done';        
?>

My script is working well. Now I have ported this script to google-appengine and now its storing invalid images. Here is app-engine script

<?php
$path = 'gs://my-bucket/test.png';

$options = ['gs' => ['Content-Type' => 'image/jpeg' , 'acl'=>'public-read']];

$ctx = stream_context_create($options); 

$put = fopen("php://input", "r");   

$fp = fopen($path, "w",false,$ctx); 

while ($data = fread($put, 1024))
    fwrite($fp, $data);     

fclose($fp);
fclose($put);

echo 'done';    
?>  

Files are created with invalid content. Can anyone help/point out what I am doing wrong?

I tried the same script and it works fine for me, might be you were facing the issue because of the size of the image, as it was an issue in the PHP library, which generates the memcache key. Memcache unable to generate the key of length more than 250 bytes.Now that that bug is fixed. Find below the code snippet which i tried.It is same as yours.

<?php
      use google\appengine\api\cloud_storage\CloudStorageTools;
      use google\appengine\api\log\LogService;

      $object_url = 'gs://my-bucket/test1.png';

     $options = stream_context_create( ['gs' => ['acl' => 'public-read', 
    'Content-Type' => 'image/jpg']] );

      $my_file = fopen($object_url, 'w', false, $options);
      $put = fopen("image.jpg", "r");

      while ($data = fread($put, 1024))
          fwrite($my_file, $data);
      fclose($my_file);
      fclose($put);

    echo 'done';    
?>