我如何获得一个随机文件's url(从目录&子目录),将其返回为id's href

how do i get a random file's url (from a directory & subdirectories) & return it to a id's href?

本文关键字:子目录 返回 id href 随机文件 一个 何获得 url      更新时间:2023-09-26

我尝试了一个php解决方案,但在我的最后一个问题中被告知我"无法通过HTTP读取/列出目录"。您需要使用不同的协议在internet上列出目录:FTP、SSH等。您需要访问远程服务器才能做到这一点。如果你唯一可以使用的是HTTP,你需要检索网页(= HTML文档)并自己解析它。"(如何得到一个php脚本打印/工作)

我希望它是简单的-我可以做HTML,我正在学习Java,我只是徘徊在PHP。

更新:为例。File.txt, file2.txt, &file3.txt都在/some/目录-我想要一个PHP脚本抓取一个随机&以一种我可以把它放在元素的href中的方式给我。如果不是PHP,还有别的吗?谢谢。

我还没有测试过。

$filenames=glob("files/*.txt");
$count=count($filenames);
if($count>0)
{
    $rndfile=$filenames[rand(0,$count-1)];
    echo '<a href="' . $rndfile . "'>Random file</a>";
}

首先需要以下文件:

<?php
    [...]
    $files = scandir(dirname(__FILE__));
    $links = array();
    foreach($files as $file)
    {
     links[] = '<a href="http://localhost/url_decoder?file="'.md5_file($filepath.$file).'"> $file';
    }
    <table>
    foreach ($links as $link){ echo "<tr><td>$link</td></tr>";}
    <table>
?>

这个小脚本扫描当前php脚本的文件路径,并在该目录下的每个文件创建一个链接到另一个php脚本,该脚本使用文件md5哈希值作为参数。那么解码器应该执行以下操作:

<?php
    [...]
    $file_search = $_GET['file'];
    $files = scandir(dirname(__FILE__));//coder and decored located in same folder
    foreach($files as $file)
    {
     if (md5_file(dirname(__FILE__).DIRECTORY_SEPARATOR.$file) == $file)
     {
      $fd = fopen (dirname(__FILE__).DIRECTORY_SEPARATOR.$file, "r")) {
      $fsize = filesize(dirname(__FILE__).DIRECTORY_SEPARATOR.$file);
      $path_parts = pathinfo($fullPath);
      $ext = strtolower($path_parts["extension"]);
      switch ($ext) {
        case "pdf":
          header("Content-type: application/pdf");
          header("Content-Disposition: attachment; filename='"".$path_parts["basename"]."'""); // use 'attachment' to force a download
       break;
       default;
         header("Content-type: application/octet-stream");
         header("Content-Disposition: filename='"".$path_parts["basename"]."'"");
      }
      header("Content-length: $fsize");
      header("Cache-control: private"); //use this to open files directly
      while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
      }
      fclose ($fd);
      exit;
     }
    }
?>

这不是完美的,一些代码取自本页,但至少给了你一个如何操作的想法。希望这对你有帮助!