PHP echoing jpeg image fails, but writing the same image to a file works fine. What for?

I have a function in PHP that calls curl to get an image. When I print this to a file and view it in a browser, the image looks great. When I use the echo of the curl results as the return value from my PHP script, the browser displays a broken image icon (see an example of this icon: http://www.artifacting.com/blog/wp-content/uploads/2007/01 /error_icon.gif ).

$ch = curl_init(); 
$options = array(
  CURLOPT_CONNECTTIMEOUT => 120,
  CURLOPT_TIMEOUT        => 120,
  CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
  CURLOPT_FRESH_CONNECT  => 1,
  CURLOPT_HEADER         => 0,
  CURLOPT_USERAGENT      => "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)",
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTPPROXYTUNNEL => 1,
  CURLOPT_POST            => 1,
  CURLOPT_RETURNTRANSFER  => 1,
  CURLOPT_BINARYTRANSFER  => 1,
);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt_array($ch, $options);
curl_setopt($ch, CURLOPT_POSTFIELDS, $param_list);

// The http response code is 200, and the body length is 50kb.  
$body = curl_exec($curl_params);

// This produces a file containing an image that looks good when viewed in a browser.
$bodyFile = @fopen("img.jpg", "w");
fprintf($bodyFile, "%s", $body. "\n");
fclose($bodyFile);

// This does not render in the browser.  Instead I see the broken image icon.
$contentType = "image/jpeg";
header('Content-type: ' . $contentType);  
echo $body;

Any ideas? Help!

+3
source share
3 answers

, PHP , . "? > ".

+1

, , cURL.

:

<?php 
$ch = curl_init ("http://www.google.com/images/logos/ps_logo2.png");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$image=curl_exec($ch);
curl_close ($ch);
header("Content-Type: image/png");
echo $image;
?>
+2

, . , - , ( , , ), script . , php.ini , script .

ASCII, - ​​. <?php . , <?php ( !), .

, , , , , .., . JPG PNG "" .

+2

Source: https://habr.com/ru/post/1767846/


All Articles