Uly.me

cloud engineer

  • Home
  • About
  • Archives
Home/PHP/How To Force Downloads

July 24, 2016

How To Force Downloads

Browsers behave differently when it comes to linking media files. Sometimes it will play them directly on the browser. Sometimes it will download them. Each browser seems to have their own rules. So, how do we force all browsers to download media files with just a click of a link.

A simple link like the one below simply won’t work.

<a href="video.mp4">Download</a>

<a href="video.mp4">Download</a>

One way of forcing downloads is to use a PHP function called readfile.

We have a file below called dl.php. We pass the filename to it, as well as set the path and URL.

$filename = $_GET['file'];
$filepath = "http://domain.com/download/";
$url = $filepath.$filename;
header("Content-disposition: attachment; filename=".$filename."");
header("Content-type: application/octet-stream");
readfile("".$url."");

$filename = $_GET['file']; $filepath = "http://domain.com/download/"; $url = $filepath.$filename; header("Content-disposition: attachment; filename=".$filename.""); header("Content-type: application/octet-stream"); readfile("".$url."");

Our HTML download link will look like this.

<a href="dl.php?file=video.mp4">Download</a>

<a href="dl.php?file=video.mp4">Download</a>

It’s one way of forcing a download via the PHP route.

Filed Under: PHP Tagged With: browser, download, readfile

Have content delivered to your mail. Subscribe below.

About Me

I'm Ulysses, Cloud Engineer at Cardinal Health based in Columbus. This blog is about Linux and Cloud technology. When off the grid, I enjoy riding my electric skateboard. I've surfed, snowboarded and played the saxophone in the past. I hope you find this website helpful. It's powered by WordPress and hosted on AWS LightSail.

  • Cloud
  • Linux
  • Git

Copyright © 2012–2021