PHP: How to output image files?

2019-08-09 10:55发布

问题:

I would like to add images to a dynamically generated page (I use my own template system) with PHP.

NOTE: I regulate image access for security reason.

The folder that contains the images is above the site root, therefore not accessible by HTML links.

I believe there is a method in which PHP returns a file as a resource, specifying the type in a header, and (correct me if I am wrong) a function specifically designed for that imagejpeg().

Please advise, and if possible write a simple example.

回答1:

What you need to do to output image files is in order:

PHP loads the image from the file, this is file_get_contents or otherwise fopen to open and access the file itself. If the file is a specific image file you can open the file with imagecreatefromjpeg() which will do just that, generate an image file from a JPEG source.

Then, once the file is loaded from anywhere on your filesystem, including directories outside of your web root, PHP can output the data caught in point 1, above, with some HTTP Headers and direct reference to the loaded image.

NOTE: this means that the sole output of this PHP file is the image, so file.php === image.jpg in this case.

So a brief example:

image is stored in /home/images/image1.jpg

PHP file runs from /home/site/imagecall.php

PHP file says:

<?php
if (file_exists('/home/images/image1.jpg')){
    $image = imagecreatefromjpeg('/home/images/image1.jpg');
    if ($image){
         header('Content-Type: image/jpeg');
         imagejpeg($image);
         imagedestroy($image);
    }  
    else {
        die("Image could not be loaded");
    }
}

This is a starting point for you and by no means an absolute guide. Explore.

Useful references:

http://php.net/manual/en/function.imagecreatefromjpeg.php

http://php.net/manual/en/function.file-get-contents.php