PHP Force to Download Images: A Step Guide – PHP Tutorial

By | September 14, 2020

The browser will display images when you have clicked an image url, however, if you wan to download an image file after clicking an image url, how to do? In this tutorial, we will use an example to show you the way.

As to image url:

If you do not want to display image 123.webp and want to download it. you should make the image url can run php script. Here is an tutorial:

Run an Image (PNG, JPG) as PHP Script: A Step Guide

Then we can download this image using php.

Download images using php

We have learned how to make php to download text or html file.

Force Download HTML and TXT Files in PHP – PHP Tutorial

We also can edit some code to make sure php can download images, such as webp, png, jpg.

Here is the example code:

$filename = '123.webp';

header("Content-Type: text/html");
/* Tell the browser how big the file is going to be */
header("Content-Length: ".filesize($filename)."\n\n");
/* force the file to be downloaded */
header("Content-Disposition: attachment; filename=$filename");

echo file_get_contents($filename)

Run this code, we can find 123.webp will be downloaded.

php force to download images - a step guide

Category: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *