TJ Sherrill
TJ Sherrill

Reputation: 2645

How to return image from php file set as img src

I am setting up a random image function but trying to prove the concept before handling the randomizer.

Right now I have a test.php file. It contains:

<?php 
$img = 'http://example.com/img.jpg';
$fp = fopen($img, 'rb');


header('Content-type: image/jpeg;');
header("Content-Length: " . filesize($img));

fpassthru($fp);
exit;
?>

And then in another html file I have <img src="test.php">

The goal is just to return the image. The image url works is right, and test.php returns a 200. But the image just shows the little broken image icon.

I have also tried readfile() with no luck.

I am just trying to show this image.

Upvotes: 0

Views: 11653

Answers (2)

Professor Abronsius
Professor Abronsius

Reputation: 33823

Another alternative would be to use some of the various built in functions for generating / manipulating images - in the case of the code below it is for a png but similar functions exist for jpg,gif and bmp.

Using a url as the filepath relies upon that setting being enabled by your host ( on dev obviously you control whether it is enabled or not )

Using these functions also gives you the possibility to add your own text at runtime, combine images and all sorts of other cool things.

<?php

    if( ini_get( 'allow_url_fopen' ) ){
        $imgPath='http://localhost/images/filename.png';
    } else {
        $imgPath=realpath( $_SERVER['DOCUMENT_ROOT'].'/images/filename.png' );
    }

    header("Content-type: image/png");
    $image = imagecreatefrompng($imgPath);
    imagesavealpha($image,true);
    imagealphablending($image,true);
    imagepng($image);
    imagedestroy($image);
?>

Upvotes: 1

helmbert
helmbert

Reputation: 38064

filesize does not work on HTTP URLs. The docs say:

This function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

However, the HTTP wrapper does not support the stat function. Because of this, you send a wrong Content-Length header and the HTTP response cannot be interpreted by your browser.

I see two possible solutions:

  1. Load the image into memory and use strlen:

    $image = file_get_contents('http://example.com/img.jpg');
    
    header('Content-type: image/jpeg;');
    header("Content-Length: " . strlen($image));
    echo $image;
    
  2. Use the $http_response_header variable to read the remote response's Content-Length header:

    $img = 'http://example.com/img.jpg';
    $fp = fopen($img, 'rb');
    
    header('Content-type: image/jpeg;');
    foreach ($http_response_header as $h) {
        if (strpos($h, 'Content-Length:') === 0) {
            header($h);
            break;
        }
    }
    
    fpassthru($fp);
    

Upvotes: 9

Related Questions