簡體   English   中英

使用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的末尾(在body標記之前),您可以在<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;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM