Jul 26, 2008

Display Random File In A Directory - how to display a random file from a set directory.

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > PHP Programming

free web hosting

Display Random File In A Directory - how to display a random file from a set directory.

wappy
hi, could someone please help me with this? I have some files in a directory and i want to know how i can randomly display link/s to one or more of the files in my directory for download. But it must not at any time display index.php which is also in the directory with the downloads.
Thanks in advance for any help given unsure.gif

Reply

BuffaloHELP
Try this for a size. It was something I was using (not random) for my game league schedule list.

CODE

<?php
$path = "../directory name of this index.php will reside/";
$narray=array();
$dir_handle = @opendir($path) or die("Unable to open $path please notify the administrator. Thank you.");
echo "You can place greeting or some message here.\n";
$i=0;
while($file = readdir($dir_handle))
{
     if($file != '.' && $file != '..' && $file !='index.php')
    {
        $narray[$i]=$file;
        $i++;
    }
}
$j = rand(0, $i-1);

echo "<a target='_blank' href='$path$narray[$j]'>$narray[$j]</a>";

//closing the directory
closedir($dir_handle);
?>

If all your files are in same extension, i.e. htm, then you can insert this code before the last echo to hide the extension.

CODE
$filename = str_replace(".htm", "", $narray[$j]);
echo "<a target='_blank' href='$path$narray[$j]'>$filename</a>";


I think the rand(0, $i-1) is correct since when existing the loop, the last value of $i is greater than $narray[$i] = $file

To show two random files

CODE

<?php
$path = "../directory name of this index.php will reside/";
$narray=array();
$dir_handle = @opendir($path) or die("Unable to open $path please notify the administrator. Thank you.");
echo "You can place greeting or some message here.\n";
$i=0;
while($file = readdir($dir_handle))
{
     if($file != '.' && $file != '..' && $file !='index.php')
    {
        $narray[$i]=$file;
        $i++;
    }
}
$j = rand(0, $i-1);
$k = rand(0, $i-1);
if ($j == $k)
{
       $k = rand(0, $i-1);
}      

echo "<a target='_blank' href='$path$narray[$j]'>$narray[$j]</a><br />";
echo "<a target='_blank' href='$path$narray[$k]'>$narray[$k]</a>";

//closing the directory
closedir($dir_handle);
?>

 

 

 


Reply

juice
Wappy you could have just used your random text/image snipet and inserted links. I've come across a few sites were they do that.
QUOTE
Ok here is some code you can use for displaying random text, images, or links....
//put this code on the page you wish to display the random text/image/link on..
CODE

<?
//random code
$xfile = @file("random.txt");
$random_num = rand (0,count($xfile)-1);
$udata = explode("::",$xfile[$random_num]);
echo "<small>$udata[1]</small><br/>";
?>

//create a text file like random.txt and put in it something like this....
CODE

::<a href="http://mradar.com/?i=22720">mRADAR.com</a>
::<a href="http://surfwap.com/?site=neocult">SurfWAP.com</a>
?>
This is the snippet from your site, can't you use it?

Reply

wappy
many thanks buffalo :-) / but juice that would mean i would have to site there and add hundreds of links to a text file.. Its to add to my download script/site which auto displays the files with icons corresponding to the extension and by adding the manual random code would defeat the purpose of the script and ruin it. Why do hard work when your computer can do it for you? :-)

Reply

juice
Ok wappy, I miss understood you. How bout trying to use the random image script? Like the one I'm using for my avatar and signature bars? I'm sure it can be modified smile.gif even thou I don't know a thing about PHP laugh.gif

Reply

beeseven
QUOTE(BuffaloHELP @ Sep 10 2006, 05:55 AM) *
To show two random files

CODE
...
$j = rand(0, $i-1);
$k = rand(0, $i-1);
if ($j == $k)
{
       $k = rand(0, $i-1);
}      
...
?>
That should be modified. There's a chance (albeit a small one) that the second time you choose $k that it will be the same as $j again. Just change "if" to "while" to remedy this.

Reply

wappy
thanks for the info :-) no i think i will just use this code juice, which random image code did you mean? The one i use is the same as my random link code with just images instead of links and a text file. It must read the files not me or the script user having to type them is boring and time wasting to type all that and the script is designed to be very simple to use with little or no setup needed.

Reply

BuffaloHELP
QUOTE(beeseven @ Sep 10 2006, 12:06 PM) *

That should be modified. There's a chance (albeit a small one) that the second time you choose $k that it will be the same as $j again. Just change "if" to "while" to remedy this.

beeseven,

Ah ha! I knew something didn't look right smile.gif Thanks for the great modification. 6am reply posts aren't the greates quality tongue.gif

Reply

Saint_Michael
in my search for good scripts and what not i have an alternative although I havn't tested it myself it could be use to help not display the index page.

http://zulumonkey.org/?id=tutorials&pa...ment&oid=70

Reply

wappy
ok thanks i will take a look at that tutorial. I think i can work out the index.php thing though as my download script already does that and my search but i built the base code so long ago i really can't remember how i done it lol, i been more busy with updating it with proper extension icons, search and the like. When/if i release it, it will be the best wap download script out, well it is already but i never give it out. Would like to say a big thanks to the creator of the wapbuddy script also for giving me a good starting point and inspiration to write the new download script :-)

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : display random file directory display random file directory

  1. How To Display Images Of A Directory - (4)
    I am trying to do a simple thing. I want to display all the images of a directory on a single page
    with the checkbox next to each image, so that i can select multi images and i can delete selected
    images. Following few lines of code display the images of a directory.. i need help to put the
    check boxes with each image. and I dont understand how can i select multi images with check box and
    then delete them. I hope someone can help. thanks. CODE <?php $path = "./";
    $dir_handle = @opendir($path) or die("Unable to open folde...
  2. Php Configuration File - "config.php" (16)
  3. Getting List Of Directories And Files Using Php - PHP Function for Directory and File List (6)
    is there a php function that lists the content of some folder.... example: /New folder new.txt
    left.gif download.zip dc.exe ....so is there..? /rolleyes.gif' border='0'
    style='vertical-align:middle' alt='rolleyes.gif' /> ...
  4. Include File.php?id=something - using the include() function (13)
    Well, I am making a full CMS system for my site, and want to make the index.php file to include the
    view.php?id=1 file. I tried with this code, but it didn't work: CODE <?php include
    'view.php?id=1' ?> This is the error I get: CODE Warning:
    main(view.php?id=1) [function.main]: failed to open stream: Invalid argument
    in C:\server\xampp\htdocs\test\index.php on line 1 Warning:
    main() [function.include]: Failed opening 'view.php?id=1' for inclusion
    (i...
  5. Script: Php Jukebox - A one file script! (4)
    This scripts is so simple, you dont need to edit ANY of it! All you have to do is make a folder
    called 'songs' and put some audio files in it. Here is the whole page, I named it index.php
    and put it in a folder called 'music': CODE <!DOCTYPE HTML PUBLIC
    "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd"> <html> <head>
    <title>PHP jukebox</title> </head> <body> <!-- ©2005 Craig
    lloyd. All rights reserved. Visit cragllo.com for more sc...
  6. Need Some Help In File Browser - listing all sub folders and files in them. (8)
    Hey I want to create a very simple file browser, so that, it reads all the sub-folders which are
    places in a directory, and the files inside the sub-folders (It reads only files inside sub-folders
    and list them in simply. ) Also, it creates a directory (any name) inside each sub folder. My
    Following code reads on the files inside the main directory, it does not read the files inside the
    sub-folders.. I appreciate any help. CODE <? $path = "./"; $dir_handle =
    @opendir($path) or die("Unable to open $path"); whil...
  7. Updating Php File Through A Web Form - (5)
    Hello, i'm not sure if this can be done with php or not but what i need is a way to make an php
    file that have an html form on it and it will take the info you put in to that form and write it to
    an existing php file, for example: if i have the file news.php and the file news_update.php. if you
    went to news_update.php you would get an form with a text area for you to write a new addition for
    the news.php file and when you hit submit it will add what you typed in the form to the file
    news.php. If this is going to be a big code or a hard one to make but some one think...
  8. Php Ftp Upload Form - Adding User Directory to PHP Upload Form - Help (0)
    Alright I am trying to have a PHP FTP Upload Form that allows the user to create the directory
    folder for where they want to upload there files to. example: Main Directory: vainsoft.com There
    directory: vainsoft.com/modeling or vainsoft.com/photography But I dont want them to be able to
    upload things into the main directory, only sub-directories, is that possible with this coding that
    I have: //uses $_FILES global array //see manual for older PHP version info //This
    function will be used to get the extension from the filename function get_extension($fi...
  9. File Checker-how To Check File Whith Html Through Html? - (2)
    edit:sorry for the mistake it is php not html and its with not whith my code checking script= CODE
    <?php $file = '$CHECK'; if (file_exists($file)) {
        echo "The file $filename exists"; } else {     echo "The file $filename
    does not exist"; } ?> my question is how to check the file whith html example:on a page
    a text box is provided and a button the user writes a file name (or website) the user clicks on the
    submit button then it checks and show it (with the code above) i got the code C...
  10. Php And Flash Image Gallery - Need some help in creating or editing an xml file while viewing some o (5)
    Hello there and thanks for the helping hand you are offering. PHP newbie here! /ph34r.gif"
    style="vertical-align:middle" emoid=":ph34r:" border="0" alt="ph34r.gif" /> So here is my problem:
    On my website I have a flash image gallery.The way the gallery works is by uploading pictures in a
    folder and editing? an xml file.(pics.xml) where it adds the following code when you upload a
    picture: CODE <pictures>     <image location="nameofpicture1.jpg"
    desc="" />     <image location="nameofpicture2.jpg" desc="" /&#...
  11. No File Extension - (3)
    On MediaWiki, the URL of the content is http://YOURWIKI.com/index.php/Blah Is it possible to
    create a page or two that doesn't have a file extension? If so, how is it done?...
  12. File Upload - File upload (1)
    I need to add a facility on my customer's website so his clients can send him jobs, typically
    5mb - 50mb. I've looked around the web and researched this, and tried a few tests (failed), but
    my brain's beginning to hurt. Could someone please tell me the best way to go about this,
    please. The site is done in Flash, but I'm sure a link to an html page would be ok if necessary....
  13. <?php ?> Unique Visitors Script - Flat file unique visitors script (no sessions) (2)
    This is really simple script. Well at least this part is, but it could be extendable. Only problem
    is that it's not really for massive websites with hundread of visitors a day, but rather for
    small ones. But it is a good script to figure out how to make a visitor counter script. Anyway
    here's the snippet. CODE <?php function getVisits($variable) {
        $visits = array();     if ($handle =
    opendir('stats/')) {     while (false !== ($file =
    readdir($handle))) {  ...
  14. Unofficial Trap17 Hosted Members Directory - (13)
    This is the Trap17 edition of the Hosted Members Directory. A script initially written by me for the
    Astahost forums. The script has gone through many a changes and is currently in version 4 which
    includes the following features:- > Listing of hosted members. > Listing of the websites of the
    hosted members. > Validation of the websites (whether the site is suspended, working or not not
    working, etc) > Save/Load result to/from database. > Multithreaded for faster operation. > Status
    messages, images and progress bar to keep you informed of the process. Link to the Scrip...
  15. How To Make A Random 7 Number Code? - (2)
    I am making a script in php, and for it I need to know how to make a random 7 digit code. I think it
    has something to do with md5, but i am not sure. Thanks! EDIT- Can someone please change the
    title to "How to make a random 7 digit code in php?" Thanks!...
  16. How To Display The Latest Forum Post On Main Page - (4)
    Hey does anyone know how to display the latest forum post on the main page of a website? I'm new
    to PHP and have no idea what to do. Thanks in advance!...
  17. [php]simple Flat File Text Manipulator - Example on how to use forms to write to files in PHP (3)
    I made a simple flat file text editor, that can show you probably how simple it is to use forms with
    php and write that data to file. This example has 2 files, submit.php, and postit.html. Submit.php
    is used to write title, and some text, and add html tags, and paragraph tags where new paragraphs
    are. Here's the file with comments. I think that HTML really doesn't need some more
    explaining. CODE Title: <br /> <input type="text"
    name="title" size="53"> <br /> Text: <br />
    <textarea nam...
  18. Edit .txt File In Ftp Via Webpage - file on external ftp (2)
    Right Im new here and stuggling with a problem im having. I've currently got a Login Script to
    login to a external ftp and it displays the folders contents, however i need it so it echos a
    specific file (coursedata.cfg) into a formarea which you can then edit the file and when u click
    save it overwrites the file with the new one. Im really quiet getting annoyed with it xD as
    everything i do ends up trying to include the file from the webserver the script is hosted on and
    not the external ftp source. thanks Full Code Bellow Simple FTP Manager body { fon...
  19. Reading Files From Directory To Array, And Using $_get To Get Them - Simple way to manage lot's of files (2)
    Some user posted a similar problem i had when i tried to figure out how to update content on my
    website in less work as possible. This is just part of the "big" plan i have for my site but it can
    be helpfull to you guys if you like FlatFile. I hope that mod's don't mind me posting the
    same code here and on their forums, couse if they do i'll delete it from their forums
    /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" /> So
    here's the situation. Let's say you have a folder called 'myfilesdirectory' on your
    s...
  20. Display The Current Date/time - With a simple PHP code (3)
    Use this code to display the current date and time. CODE <?php   $date =
    date('l dS \of F Y h:i:s A');   echo "$date"; ?>
    "l" would display the current day of the week such as Sunday. d displays the day of the month...
    such as 1 and S adds the appropriate suffix(st). /of simply displays the word "of". F displays the
    current month with no abbreviations while Y displays the four digit year(2007). "h" displays the
    current hour with leading zeros if necessary(Ex. 06 for 6 o'clock). "i" displays the m...
  21. Php Help Needed Including File In A Page. - (2)
    i'm a noob in php programming, i can understand and modify php programs, but i dont know to
    write on my own. So please somebody who is well versed in php help me. My need is, I'm
    currently builiding a knowledge base website , i've my own design for the website, check here,
    http://laschatz.info/kzone/ Each page in the left hand site has a tree navigation of all the
    topics available. Since this information must be same in all the pages, presently I need to change
    all the pages after adding a new category. Could you please help me in such a way that I can ad...
  22. Help Php: How To Load String From Text File (solved) - Loading string from text file when you click on your link (9)
    I learned the way to load other files with the code posted on this forum. Now i wanted to try
    something for my side menu. I am calling this a string, --> $tekst , maybe it's
    called something else i'm not sure Now let's say i have a file called details.txt In that
    file i would like to have something like this $detailsaboutphp1 = ("details details details
    1"); $detailsaboutphp2 = ("details details details and even more details 2"); How to make a
    code that loads those $strings on click of a mouse. When we tried to load extern...
  23. I Need Help With File Edit In Php - with ftp (6)
    Currently i have CODE <?php if($_POST['user']=="" or
    $_POST['pass']=="" or $_POST['host']==""
    or $_POST['root']=="" or
    !isset($_POST['run'])){  print('<form method=post
    name=form>');  print('FTP username <input type=\'text\'
    name=user value=""><br>');  print('FTP password <input
    type=\'password\'...
  24. Help Needed With Directory/file Listing Code Infinite Loop - Made an infinite loop but why is this so? (5)
    Hi all ive got a small and simple (for the moment atleast /unsure.gif"
    style="vertical-align:middle" emoid=":unsure:" border="0" alt="unsure.gif" /> )file and directory
    listing script in php as follows CODE $dir = "."; $num = 0; $file =
    scandir($dir); while($file = scandir($dir)){     echo
    $file[$num];     echo "<BR>";     $num = $num + 1;     
    }; the concept is simple enough, the directory to start with is the current one, so scan this
    directory and wh...
  25. Changin My Phpnuke Directory...please Help - (13)
    ok i wus fantastico to install my nuke...it asked me to give it a name for its directory so ive put
    down "nuke" so to get to my site ud have to go to www.boaw.trap17.com/"nuke" but now i want to
    change nuke into something else more related to the site...i was wondering if any1 can tell me the
    best way to do that...thanks...
  26. Display MySQL results in a Table - question (8)
    hi all i know php and my sql i want to know how can show mysql result in this tabel for example :
    CODE <table cellpadding="0" cellspacing="0" width="200"
    height="151">     <!-- MSTableType="layout" -->     <tr>
            <td height="21" width="100" valign="top">1</td>
            <td height="21" width="100" valign="top">8</td>
        </tr>     <tr>         <td height="21" width="100" valign=&...
  27. How To Sort Files Of A Directory using Php - (11)
    The following code displays the files of folder...but they are displaced by the order of adding... i
    want to sord the files / folders alphabetically and sord by accending order and by decending
    order.. can some one help me. $path = ""; $dir_handle = @opendir($path) or
    die("Unable to open $path"); echo "Directory Listing of $path "; while($file =
    readdir($dir_handle)) { if(is_dir($file)) { continue; } else
    if($file != '.' && $file != '..') { echo " $fi...
  28. File Format Unknown! (wap) - someone PLEASE HELP! (6)
    hi people :-) listen please can someone help me find the error in this wapsite page, its driving me
    nuts! It works fine on some phones but not on others (giving a file format unknown error) and im
    having serious problems finding the error but i bet its something stupid/simple. CODE <?php
    include ("config.php"); include ("core.php");
    header("Content-type: text/vnd.wap.wml"); header("Cache-Control:
    nostore, nocache, mustrevalidate"); print "<?xml version=\"1.0\&#...
  29. Displaying Files Of A Directory - (2)
    I want to display the contents of a directory.. i have the following code.. It gives the output in
    one column only... like file1 file2 file3 file4 . . . . . Since there are lot of files so this
    column gets very long..i want to display the x number of files in each column.. like if there are 22
    files.. then file 1 file 11 file 21 file 2 . file 22 file 3 .. . . . file 10
    file 20 This was just an example..I know it can be done by using but i dont know how to do it
    with loop. Please help me. QUOTE $dir = './'; $handle =...
  30. File In Database - Question.thanks (1)
    Hi all i write this code i want when you see download.php (this code) my file goes for download for
    user sorry my english is not very good its a file database project for my university but when i
    browse this code my soruce file (.zip) echo in my page and dont goes for download my next querstion
    about safe mode i saw (php.net and zend) when safemode is on file databaseing and header() is not
    working . is it true ? if is it true i save my file at hosting and no (database) i want write
    standard script . plz help me thanks more and more CODE include("config.php&...



Looking for display, random, file, directory, display, random, file, set, directory

Searching Video's for display, random, file, directory, display, random, file, set, directory
How To
Display
Images Of A
Directory
Php
Configuratio
n File
"config.
php"
Getting List
Of
Directories
And Files
Using Php
PHP Function
for
Directory
and File
List
Include
File.php?id=
something
using the
include()
function
Script: Php
Jukebox A
one file
script!
Need Some
Help In File
Browser
listing all
sub folders
and files in
them.
Updating Php
File Through
A Web Form
Php Ftp
Upload Form
Adding User
Directory to
PHP Upload
Form - Help
File
Checker-how
To Check
File Whith
Html Through
Html?
Php And
Flash Image
Gallery Need
some help in
creating or
editing an
xml file
while
viewing some
o
No File
Extension
File Upload
File upload
<?php
?> Unique
Visitors
Script Flat
file unique
visitors
script (no
sessions)
Unofficial
Trap17
Hosted
Members
Directory
How To Make
A Random 7
Number Code?
How To
Display The
Latest Forum
Post On Main
Page
[php]simple
Flat File
Text
Manipulator
Example on
how to use
forms to
write to
files in PHP
Edit .txt
File In Ftp
Via Webpage
file on
external ftp
Reading
Files From
Directory To
Array, And
Using
$_get
To Get Them
Simple way
to manage
lot's of
files
Display The
Current
Date/time
With a
simple PHP
code
Php Help
Needed
Including
File In A
Page.
Help Php:
How To Load
String From
Text File
(solved)
Loading
string from
text file
when you
click on
your link
I Need Help
With File
Edit In Php
with ftp
Help Needed
With
Directory/fi
le Listing
Code
Infinite
Loop Made an
infinite
loop but why
is this so?
Changin My
Phpnuke
Directory...
please Help
Display
MySQL
results in a
Table
question
How To Sort
Files Of A
Directory
using Php
File Format
Unknown!
(wap)
someone
PLEASE
HELP!
Displaying
Files Of A
Directory
File In
Database
Question.tha
nks
advertisement



Display Random File In A Directory - how to display a random file from a set directory.



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE