Sikander
Sikander

Reputation: 2835

PHP/ HTML: Download PDF link working on page load

I'm using following code

<?php
$file = 'COMPANY_PROFILE.pdf';

if (! file) {
    die('file not found'); //Or do something 
} else {
    // Set headers
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");
    // Read the file from disk
    readfile($file); 
}

This automatically gives a download file prompt and if i use something like this:

<a href="COMPANY_PROFILE.pdf" target="_blank" ">Download PDF </a>

it opens the PDF in the browser, so how do I fix this issue in a way that file gets downloaded on button click?

Upvotes: 0

Views: 1084

Answers (1)

K. Uzair
K. Uzair

Reputation: 303

You can achieve your desired results by different methods. In this way what you are doing right know you are telling php to look for a file if it doesn't exist just show that file doesn't exit other wise show document that exist.

But what you are looking for should perform on some kind of an event. e.g Button Click.

You can achieve this by these kind of method.

AJAX Call

By an ajax call on click on a button to go to this php function.

Posting PHP

Either you can post some thing to PHP and in your PHP code you can tell your code if this specific name has been posted then download pdf otherwise not to.

Upvotes: 1

Related Questions