Skip to content Skip to sidebar Skip to footer

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 use a different protocol to list a directory over the internet: FTP

Solution 1:

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

Solution 2:

First you need the files:

<?php
    [...]
    $files = scandir(dirname(__FILE__));
    $links = array();
    foreach($filesas$file)
    {
     links[] = '<a href="http://localhost/url_decoder?file="'.md5_file($filepath.$file).'"> $file';
    }
    <table>
    foreach ($linksas$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 folderforeach($filesas$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 downloadbreak;
       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 directlywhile(!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!

Post a Comment for "How Do I Get A Random File's Url (from A Directory & Subdirectories) & Return It To A Id's Href?"