开发者

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


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.


<?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();

?>


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

}


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜