如何使用PHP单击文件名下载文件?

OM *_*ity 5 javascript php ajax

我有一个信息列表,其中有一个字段名称是超链接的字段.我希望用户在点击它时下载该特定文件.

那么,如何使用PHP单击文件名下载文件?

我尝试使用ajax,其代码如下,但我没有下载任何文件.

的download.php

$filename = $_GET['val'];
         // Fetch the file info.
 $filePath = $_SERVER['DOCUMENT_ROOT'] . "/dfms/images/docs/".$filename;

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
Run Code Online (Sandbox Code Playgroud)

javascript函数

<script>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest();          } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function download(path,val) {
var req = Inint_AJAX();
req.open("GET", path+"download.php?val="+val); //make connection
//req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
req.onreadystatechange = function () {
 if (req.readyState==4) {
      if (req.status==200) {

      }
 }
};

}
</script>
Run Code Online (Sandbox Code Playgroud)

链接下载

<a href="javascript:download('http://localhost/project/images/','DMS.doc');">DMS.doc</a>
Run Code Online (Sandbox Code Playgroud)

Pek*_*ica 6

那么,如何使用PHP单击文件名下载文件?

最简单的方法应该是链接到它.

<a href="download.php?......" target="_blank">DMS.doc</a>
Run Code Online (Sandbox Code Playgroud)

  • 使用AJAX不会使其安全.您需要使用会话或类似方法在服务器上保护它. (2认同)