1

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">';

Kaare
  • 39
  • 4

3 Answers3

3

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");
KhorneHoly
  • 4,666
  • 6
  • 43
  • 75
  • 1) Content type should be `image/png` for png files 2) better use `readfile(...)` – Ziumin Dec 29 '14 at 11:48
  • Thank you. That was what I searched for. – Kaare Dec 29 '14 at 11:49
  • `image/jpg` and `.png`? – vladkras Dec 29 '14 at 11:49
  • I didn't noticed the `png`, edited it into the answer. Never worked with readfile, so I don't know if it's better or not, but it works for me – KhorneHoly Dec 29 '14 at 11:50
  • also `__DIR__` will return you current location of script file, not root directory, so if you have this code in say `/modules/images/functions.php` your image path will be `/modules/images/iamges/protected/...` – vladkras Dec 29 '14 at 12:15
  • @vladkras according to the question there's no other path where the script lies in. But in theory you're right – KhorneHoly Dec 29 '14 at 13:21
2
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

Community
  • 1
  • 1
vladkras
  • 16,483
  • 4
  • 45
  • 55
-1

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);
Justinas
  • 41,402
  • 5
  • 66
  • 96