我需要在点击wordpress中的链接时下载文件。我有文件网址。我知道 php 中的下载代码,并添加了函数.php。
function downloadFile($f){
header('Content-Disposition: attachment; filename=' . urlencode($f));
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
header('Content-Description: File Transfer');
header('Content-Length: ' . filesize($f));
echo file_get_contents($f);
}
现在如何在单击链接时调用此函数?link
在带有链接的页面上:
<a href="download.php?f=foo">Download "Foo"</a>
在download.php
(或您选择的任何名称)上:
include "functions.php";
downloadFile($_GET["f"]);
exit;
编辑 或者只创建一个download.php
页面:
<?php
if(isset($_GET["f"])){
$f = $_GET["f"];
header('Content-Disposition: attachment; filename='.urlencode($f));
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
header('Content-Description: File Transfer');
header('Content-Length: ' . filesize($f));
echo file_get_contents($f);
}
exit;
?>
您可以做的不是创建一个函数,而是在 Wordpress 后端创建一个新页面,并将您的 php 标头放在该页面的自定义模板中,如下所示(简单的 pdf 下载):
<?php
// Specify wordpress template name
/* Template Name: Download Page */
// We'll be outputting a PDF
header('Content-type: application/pdf');
// Set filename of download
header('Content-Disposition: attachment; filename="FILENAME.pdf"');
// Path to the file (searching in wordpress template directory)
$url = get_template_directory_uri() . "/folder/ORIGINAL_FILE.pdf";
readfile($url);
?>
然后,您可以简单地将新wordpress页面的永久链接作为下载链接上的href。WordPress页面的永久链接可以在wordpress后端随意编辑,因此您可以将其设置为:
www.example.com/downloadfile
我知道它很旧,但我最近也遇到了这个问题,希望它也能帮助任何最终来到这里的人!