1

code.php

$code = $_GET["code"];
$file = 'code/'.$code.'.html';

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));
    readfile($file);
    exit;
}

Generated URL to download the file:

http://www.example.com/code.php?code=yoursite.com_nbsp63ibrf

Well, I want to forcing download the html file, above code not working and it just preview the file at browser!

Pedram
  • 15,766
  • 10
  • 44
  • 73
  • Take a look here http://stackoverflow.com/questions/20508788/do-i-need-content-type-application-octet-stream-for-file-download – SergkeiM Jan 15 '16 at 08:58

5 Answers5

1

file_exists() returns false. Change your path with document root:

$code = $_GET["code"];
$file = $_SERVER['DOCUMENT_ROOT'] . '/code/' . $code . '.html'; // set your path from document root.
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));
    readfile($file);
    exit;
}
schellingerht
  • 5,726
  • 2
  • 28
  • 56
0

This is actually not possible. The browser can always decide on its own, if the file should be downloaded or not.

The furthest you can go is sending the content-disposition header.

Julian F. Weinert
  • 7,474
  • 7
  • 59
  • 107
0

Try changing the content type to match the file type and setting the transfer encoding to binary:

header('Content-Transfer-Encoding: binary');
header('Content-Type: text/html');
Rainner
  • 589
  • 3
  • 7
0

Try this

$code = $_GET["code"];
$file = $_SERVER['DOCUMENT_ROOT'] . '/code/' . $code . '.html'; // set your path from document root.
if (file_exists($file)) {
    header("Content-Type: text/html");
    header("Content-Type: application/force-download");   
    header("Content-Type: application/octet-stream");   
    header("Content-Type: application/download");     
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
Ninju
  • 2,522
  • 2
  • 15
  • 21
0

unfortunately it was a encoding issue. I changed code.php encoding from UTF-8 to UTF-8 Without BOM then problem solved. Thanks for all answers and helps. I forgot that PHP header only works with UTF-8 Without BOM.

Pedram
  • 15,766
  • 10
  • 44
  • 73