PHP Show Images (PNG, GIF, JPEG, WebP) in Browsers: A Completed Guide

By | April 16, 2020

We often need to read an image file content and process it, then display this image in browsers. How to show them using php? In this tutorial, we will introduce you how to do.

Preliminary

To make php can output images in browser, you should using send image type headers.

Headers of image are below:

Image Mime Type
PNG image/png
GIF image/gif
JPEG image/jpeg
JPG image/jpeg
WebP image/webp
ICO image/x-icon

How to show images in browser using php?

We will display a webp file as an example:

<?php
$img = '1.webp'
header('Content-Type: image/webp');
echo file_get_contents($img);
?>

Moreover, if you plan to the browser can cache images, you can do like this:

$t=24; // hours
$time=time();
$interval=3600*$t;

// if cached, do not read image data
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
    $modified_time = @$_SERVER['HTTP_IF_MODIFIED_SINCE']; 
    if( strtotime($modified_time)+$interval > time() ){ 
        header("HTTP/1.1 304"); 
	exit; 
    } 
}

$img = '1.webp'

header('Cache-Control: public');
header('Last-Modified: '.gmdate('r',$time));
header('Expires: '.gmdate('r',($time+$interval)));
header('Cache-Control: max-age='.$interval);
header('Content-Type: image/webp');
echo file_get_contents($img);

In this code, we will make our browser cache the image data one day.

Category: PHP

Leave a Reply