在我的 Wordpress 插件中,我在受限文件夹中创建了一个文件。
如何生成一个下载脚本以将其用作 html 非直接链接?
换句话说,我希望文件的真实路径不要显示在链接的“href”上,而是从后端函数检测并添加。
前端 html 类似于:
<a href="/download?fn=filename.ext">Download my file</a>
但是青色文件路径/名称将是“/restricted-dir/filename.ext”。
最后我自己解决了这个问题。 在我的插件中,我创建了一个“脏”自定义端点来为受限文件夹(在非公共位置)中的任何现有文件提供服务。
define( 'RESTRICTED_DOWNLOAD_DIR', '/restricted-dir/' );
add_action( 'parse_request', 'parse_request_endpoint' );
function parse_request_endpoint($wp) {
//endpoint url
$endpoint="download";
if ( $endpoint == $wp->request ) {
@$fn=sanitize_file_name($_GET["fn"]);//As from suggestion for security reasons
$filename=RESTRICTED_DOWNLOAD_DIR.$fn;
if(is_file($filename)){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
unlink($filename);//If served just once
exit;
}
}
}
然后我可以使用 html 输出的函数 ant 从代码或短代码中调用它:
function my_file_link(){
$filename="myfile.ext";//this file must exist in RESTRICTED_DOWNLOAD_DIR
$html="<a href=\"/download?fn=$filename\">Download my file</a>";
return $html;
}
这样,如果找到文件就会下载,但如果在没有正确参数的情况下调用 URL,Wordpress 将显示 404 页面。可以改进该解决方案,在下载端点中添加阻止逻辑。
我认为本教程指南对您有帮助。如果您想了解如何在 WordPress 上创建下载页面而无需仅使用插件 php 代码。 点击这里