Mark Henry
Mark Henry

Reputation: 2699

Transferring and displaying image from remote location

I need to read an image (based on HTTP) on an SSL connection. This script reads the image location and encodes/decodes it, then transfers the file contents and returns the image. However, I keep getting the error cannot be displayed because it contains errors.

Here is my code:

<?php   
$image = 'http://www.teleovronnaz.ch/webcam/ovronnazweb.jpg';

$info = getimagesize($image);
$strFileExt = image_type_to_extension($info[2]);

  if($strFileExt == '.jpg' or $strFileExt == '.jpeg'){
    header('Content-Type: image/jpeg');
  }elseif($strFileExt == '.png'){
    header('Content-Type: image/png');
  }elseif($strFileExt == '.gif'){
    header('Content-Type: image/gif');
  }else{
    die('not supported');
  }
  if($strFile != ''){
    $cache_ends = 60*60*24*365;
    header("Pragma: public");
    header("Cache-Control: maxage=". $cache_ends);
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_ends).' GMT');

$img_safe = file_get_contents($strFile);
echo $img_safe;
  }
  exit;
?>

Upvotes: 1

Views: 52

Answers (2)

maio290
maio290

Reputation: 6732

I don't know why you do it so complicated. I just stripped your cache handling, but really

<?PHP
$image = 'http://www.teleovronnaz.ch/webcam/ovronnazweb.jpg';
$imageContent = file_get_contents($image);
header("Content-Type: image/jpeg");
echo $imageContent;
die(1);
?>

Is enough to display the image. No base64 or additional stuff needed. And if the url is static, you don't even need the distinction of the file extension. You stated an image - that's singular. So I'm guessing that's the only use case here.


I just took some more time to explain a few things:

read an image (based on HTTP) on an SSL connection

If it's HTTP, there is no SSL. That's what HTTPS is for.

This script reads the image location and encodes/decodes it,

I don't know what you think, but it is not. It is base64_encoding the URL to directly decode it again into another variable. That's like doing the following: 0 is your $image - then you make $image+1 (base64_encode) - which will result in 1 - then you do $image-1 (base64_decode) which will result in 0 again.

Upvotes: 0

Saif
Saif

Reputation: 2989

This worked for me.

<?php
$url = 'http://www.teleovronnaz.ch/webcam/ovronnazweb.jpg';
header('Content-type: image/jpeg');
readfile($url);
?>

Upvotes: 1

Related Questions