Mohan Ram
Mohan Ram

Reputation: 8463

To make html file downloadable

i had a html file "sample.html" I need to make user to download this file by clicking a button in a page.

How to make html file as downloadable using php

Upvotes: 0

Views: 974

Answers (4)

maus
maus

Reputation: 182

<?php

$output_file = "example_name.html";

header('Pragma: no-cache"');
header('Expires: 0'); 
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header('Content-Transfer-Encoding: none');

//This should work for IE & Opera
header('Content-Type: application/octetstream; name="' . $output_file . '"');
//This should work for the rest
header('Content-Type: application/octet-stream; name="' . $output_file . '"');

header('Content-Disposition: inline; filename="' . $output_file . '"');

include "your_html_file.html";

exit();

?>

Upvotes: 1

joelcox
joelcox

Reputation: 582

Simply put, you need to read the file, set the correct headers and echo the file.

header('Content-disposition: attachment; filename=' . $file_name);
header('Content-type: ' . $file_mime);
$file_content = file_get_contents($file_location);
echo $file_content;

Link the button to the PHP file, and voila.

Upvotes: 4

Nextneed
Nextneed

Reputation: 1069

you can create a page like this

// definisco una variabile con il percorso alla cartella
// in cui sono archiviati i file
$dir = "/root/www/download/";

// Recupero il nome del file dalla querystring
// e lo accodo al percorso della cartella del download
$file = $dir . $_GET['filename'];

// verifico che il file esista
if(!file)
{
  // se non esiste chiudo e stampo un errore
  die("Il file non esiste!");
}else{
  // Se il file esiste...
  // Imposto gli header della pagina per forzare il download del file
  header("Cache-Control: public");
  header("Content-Description: File Transfer");
  header("Content-Disposition: attachment; filename= " . $file);
  header("Content-Transfer-Encoding: binary");
  // Leggo il contenuto del file
  readfile($file);
}

then you can call it passing the filename

force-download.php?filename=sample.html

Upvotes: -1

Vikram.exe
Vikram.exe

Reputation: 4585

You can use document.documentElement.outerHTML to get the HTML source for the page, then use the FileSystemObject (or some other equivalent api) to save it off to disk. You'll need Low security settings to get this to work without a prompt.

Here is a simple java script (IE specific):

function SaveToDisk(sPath)
{
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fileDest = fso.CreateTextFile(sPath, true);
    if (fileDest)
    {
       fileDest.Write(document.documentElement.outerHTML);
       fileDest.close();
    }

}

Upvotes: -1

Related Questions