Make link prompt visitor to download .PDF, .DOC, or other files

Updated: 07/13/2023 by Computer Hope
Note

This page is for Webmasters who want .PDF, .DOC, or another file link to open in a specific way, not: How to change browser download settings for PDF files.

Adobe PDF logo

In some situations, developers want to create a web page with links to an Adobe Acrobat .PDF, Microsoft Word .DOC, Microsoft Excel .XLS, or external program files. In these cases, they may want the browser to prompt to download the file instead of opening the file. There are a few different methods you use to achieve this effect.

Save / Save As option

Create a link to download the file on the web page using the <A HREF> HTML tag. Then, recommend to the web page viewer that they right-click the link and choose the option to Save or Save as the file. Viewers can then download and save the file to their computer.

Zip the file

Compress the file and create a .ZIP file or another compressed file format. Then, create a link to download the file on the web page using the <A HREF> HTML tag. By compressing the file into a ZIP file and creating a link to it, a web browser cannot directly open the ZIP file. Instead, it prompts the user to download the ZIP file or automatically download the ZIP file.

For example, the below HTML (HyperText Markup Language) hyperlink would allow a web page viewer to download a file named example.zip, containing the file you compressed to create the ZIP file.

<a href="https://www.computerhope.com/example.zip">Example file</a>

PHP scripting

Create the below PHP (PHP: Hypertext Preprocessor) file that opens .PDF files. It can also be modified to allow for the downloading of .DOC or other files.

  1. Create a new file named download.php
  2. After creating the file, copy and paste the below code into the PHP file.
<?php if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) { header('Content-Type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
}
} else {
header("HTTP/1.0 404 Not Found");
echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}
?>
  1. Save the file and upload to the server hosting the web page.
  2. Once uploaded, links to download a PDF (Portable Document Format) file need to point to download.php?file=example.pdf, where example.pdf is the name of the PDF file you want users to download.

Below is an example of a full link using the PHP scripting.

<a href="https://www.computerhope.com/download.php?file=example.pdf">Click here to download PDF</a>