Kaare
Kaare

Reputation: 39

PHP display image without HTML

How may I display an image without using any kind of HTML.

Let's say I have some protected images, which may only be shown to some users. The protected image is in directory images/protected/NoOneCanViewMeDirectly.png

Then we have a PHP file in the directory images/ShowImage.php, which check if the user is permitted to view the image.

How may I display the image using PHP only.

If you're not sure what I mean this is how I want to display the image. http://gyazo.com/077e14bc824f5c8764dbb061a7ead058

The solution is not echo '<img src="images/protected/NoOneCanViewMeDirectly.png">';

Upvotes: 1

Views: 1862

Answers (3)

vladkras
vladkras

Reputation: 17228

if (<here your logic to show file or not>)
    $path = $_SERVER["DOCUMENT_ROOT"].<path_to_your_file>; // to get it correctly
    $ext = explode(".", $path);
    header("Content-Type: image/".array_pop($ext)); // correct MIME-type
    header('Content-Length: ' . filesize($path)); // content length for most software
    readfile($path); // send it
}

Note: 1. image/jpg is not correct MIME-type, use image/jpeg instead (additional check needed), 2. readlfile() is better than echo file_get_contents() for binary data, 3. always try to provide content length for browsers and other software

Upvotes: 2

Justinas
Justinas

Reputation: 43451

You can use imagepng to output png image to browser:

$im = imagecreatefrompng("images/protected/NoOneCanViewMeDirectly.png");

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);

Upvotes: -1

KhorneHoly
KhorneHoly

Reputation: 4766

You could just header out the image with the following syntax

header("Content-type: image/png");
echo file_get_contents(__DIR__."/images/protected/NoOneCanViewMeDirectly.png");

Upvotes: 4

Related Questions