开发者

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

I tried a php solution but was told in my last question I "can't read/list a directory over HTTP. You'll need to 开发者_StackOverflow中文版use a different protocol to list a directory over the internet: FTP, SSH, etc. You'll need access to the remote server to do this. If the only thing you can use is HTTP, you'll need to retrieve the webpage (= the HTML document) and parse it yourself." ( How to get a php script to print/work )

I would like it to be simple - I can do HTML, I am learning Java, and I am just floundering around with PHP.

Update: an example. file.txt, file2.txt, & file3.txt are in /some/directory - I want a PHP script to grab one RANDOMLY & give it to me in a way I can put it in the href of an element. If not PHP, something else? thanks.


I haven't tested this.

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


First you need the files:

<?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>
?>

This little script scans the filepath of the current php script and creates one link per file in that directory to another php script that uses the file md5 hashed value as a parameter. Then the decoder should fo the following:

<?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;
     }
    }
?>

This is not perfect, and some of the code was taken from this page but at least gives you an idea how to operate. Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜