我试图在使用 readfile 在 php 中打开页面时强制下载,但它不起作用。当我转到网址 https://www.inbrax.cl/belong-gracias/?docsbelong=BELONG-DICCIONARIO-CAP-1.pdf 时,它会显示错误消息:“El archivo no Existe。”,但是如果我 console.log $fileName 和 $filePath 它显示了正确的信息。它只是不执行下载。
我才开始使用 php,所以我不确定错误是什么。
我尝试过调整标题并更改路径,但还没有成功。
这是我的代码:
<?php
if(!empty($_GET['docsbelong'])){
// Define file name and path
$fileName = basename($_GET['docsbelong']);
$filePath = './pdf/'.$fileName;
if(!empty($fileName) && file_exists($filePath)){
// Define headers
header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($fileName);
exit;
}else{
echo 'El archivo no existe.';
}
}
?>