Pedram
Pedram

Reputation: 16575

PHP - Forcing download a file not working

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!

Upvotes: 1

Views: 93

Answers (5)

Julian F. Weinert
Julian F. Weinert

Reputation: 7560

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.

Upvotes: 0

Pedram
Pedram

Reputation: 16575

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.

Upvotes: 0

Ninju
Ninju

Reputation: 2530

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;
}

Upvotes: 0

Rainner
Rainner

Reputation: 589

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');

Upvotes: 0

schellingerht
schellingerht

Reputation: 5796

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;
}

Upvotes: 1

Related Questions