PHP stream_copy_to_stream generates leading and trailing garbage corrupting content of the stream

StackOverflow https://stackoverflow.com/questions/19652270

  •  01-07-2022
  •  | 
  •  

Question

I am trying to forward image from one server to another. Thanks to ZF2 it is not that easy as it should be. What I have already is below. As a result, the image is corrupted - firebug says that there is no response content. I can echo stream content and it looks fine (a lot of artifacts etc means that image has been downloaded correctly) So how to return content that I have in stream as an image? Maybe there is some corruption due badly handled streams?(I am not a php programmer)

    $response = new \Zend\Http\Response\Stream();
    $response->setStatusCode(200);
    $headers = new \Zend\Http\Headers();
    $headers->addHeaders(array(
        'Content-Type' => 'image/jpeg',
    ));
    $response->setHeaders($headers);
    $fh = @fopen('php://memory', 'wr');
    $count = stream_copy_to_stream(fopen($url, 'r'), $fh); // URL is OK if I paste it into browser - got image
    rewind($fh);
    //  echo stream_get_contents($fh); // it would look like garbage but means that image is downloaded
    $response->setStream($fh);
    return $response;

EDIT: This is for sure PHP stream handling issue. I have compared downloaded content with original image, and I have found out, that there is some kind of leading and trailing garbage in file. Downloaded content starts with 0D 0A whitch is carrage return. Where did that come from?

Was it helpful?

Solution

I have found solution to my issue. The point was indeed in leading 0D 0A. Accidently I have found this SO topic about outputing currupted files. All i needed to do is to remove ?> from end of source of my controller, and leading new line is gone. I dont't understand why this even get to the output in all. Whith all of that i think that PHP... well you know what. It just should be gone from IT scene IMHO. Anyway sqrt(-1) loves php === so_true)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top