-1

I have this code snippet I found here: How to make PDF file downloadable in HTML link?

I tried altering it since my PDF files are in a "resources" directory.

I thought I had it correct, but it is not working.

Can someone explain what I did wrong?

<?php
if (isset($_GET["file"]) && !empty($_GET["file"])) {
$file = $_GET["file"];
$path = "/resources/";
$getFile = $path.$file;
if (file_exists($getFile)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(basename($getFile)));
// header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($getFile));
ob_clean();
flush();
readfile($getFile);
exit;
}
}
?>

I added the isset part because without it, if there wasn't a variable set then it was throwing an error.

That works fine, but when I added $path = "/resources/"; and $getFile = $path.$file; it doesn't do anything(no errors either).

EDIT: What is not working? The files are not downloading.

Tested In: Internet Explorer and Google Chrome.

EDIT 2: The links on my pages look as follows:

<a href="?file=kansasHandbook.pdf">Download PDF File</a>
Community
  • 1
  • 1

2 Answers2

0

Posting this answer to my own question for anyone viewing:

I found this code snippet that works while mine does not.

<?php
if(isset($_GET['file']))
{
$var_1 = $_GET['file'];
//    $file = $var_1;

$dir = "resources/"; // trailing slash is important
$file = $dir . $var_1;

if (file_exists($file))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
} //- the missing closing brace
?>

While this does work I am still curious as to what I did wrong in my code so that I may learn from it. :)

This snippet came from: How to download a file from specific directory using php header

Community
  • 1
  • 1
0

Change path from the absolute path

$path = "/resources/";

to a relative path:

$path = "./resources/";

or enter the full absolute path, maybe something similar like:

$path = "/var/www/htdocs/design/resources/";
hellcode
  • 2,678
  • 1
  • 17
  • 21