使用 PHP 将链接的动态 href 分配给另一个链接


assigning dynamic href of a link to another link with PHP

我有这个问题。在我的网站上,我想显示带有链接的文件夹的内容。如果我单击此链接,我希望它将文件的来源分配给另一个链接/按钮。因此,如果我单击下载按钮,它会下载我单击的文件。

这是我将文件显示为链接的内容:

.PHP

<?php
$path = "./files";
$dir_handle = @opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle)) {
  if($file == "." || $file == ".." || $file == "index.php" )
  continue;
    echo "<a href='"".$path."/".$file."'">$file</a><br />";
}
closedir($dir_handle);
?>

所以这会为文件夹中的每个文件创建一个链接,但我无法弄清楚如何将我单击的文件的来源分配给下载按钮/链接。至少我不知道一种不为每个文件制作下载链接的方法。

试试这个,注意这可能不起作用,这取决于服务器和 php 设置。我假设您使用的是正确配置的Apache(或Apache比较)服务器:

<?php
// Get the document root the server or virtual host is pointing to
$docroot = $_SERVER['DOCUMENT_ROOT'];
$docrootLen = strlen($docroot);
// realpath to get the full/expanded path to the files directly
$path = realpath('./files');
$dir_handle = @opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle)) {
    if($file == "." || $file == ".." || $file == "index.php" )
        continue;
    // Create fileUrl by removing $docroot from the beginning of $path
    $fileUrl = substr($path, strpos($path, $docroot) + $docrootLen) . '/' . $file;
    echo '<a href="' . $fileUrl . '">', $file, '</a><br />';
}
?><a id="download-button"></a><?php
closedir($dir_handle);

对于"另一个链接"部分,请注意我在上面添加了一个额外的锚标签,ID 为"下载按钮"。这将是下载按钮。在 HTML 的末尾(在结束正文标记之前),您可以在 <script> 标记中添加此脚本:

var links = document.getElementsByTagName("a"), linkIdx;
for( linkIdx in links ) {
    if( links[linkIdx].getAttribute("id") == "download-button" ) {
        // These are not the anchor tags you are looking for...
        continue;
    }
    links[linkIdx].addEventListener("click", function(e){
        // When the user clicks the link, don't allow the browser go to the link:
        e.preventDefault();
        document.getElementById("download-button").setAttribute("href", this.getAttribute("href"));
        document.getElementById("download-button").innerHTML = this.innerHTML;
    });
}