How To

How to Force Image Download in PHP From a Link

Force image download is mandatory in some content downloading websites to provide a good and smooth user experience. Even more, we have to allow direct download of an image from a link.

If we provide an image link to the user for downloading, the browser will open that image in its self rather than downloading it. No one likes to open another website link from their website.

We can provide another PHP file link that can force download an image from a link to the user’s browser to resolve this issue.

Read Also: Force Download File Using PHP

Force Download an Image Using PHP

Here, we will learn how to force download an image file using PHP. Generally, browsers open an image link with in the browser. However, the below code will help to force download an image via the link.

<?php
//file path in server
$file_path = "https://errorsea.com/wp-content/uploads/2019/04/WhatsApp-Image-2019-04-13-at-22.00.11.jpeg";

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Expires: 0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));

// Clear output buffer
flush();
readfile($file_path);
exit();
?>

Conclusion

In this article, we learned how to force download images using PHP code. I hope now you can implement the above force download images in PHP code.

Happy Coding 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

5 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago