Add to Google

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

free web hosting
Open Discussion > CONTRIBUTE > Computers > Programming Languages > PHP Programming

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*

Recent Queries:-
  1. surfwap - 210.65 hr back. (1)
  2. directory - 383.86 hr back. (1)
  3. surfwap problem - 613.57 hr back. (1)
  4. surfwap downloads - 850.93 hr back. (1)
  5. "vbscript" "random file" - 960.50 hr back. (1)
  6. "vbscript" random file from directory - 960.70 hr back. (1)
  7. loaging a random file - 1093.18 hr back. (1)
  8. manually display random file - 1331.11 hr back. (1)
Similar Topics

Keywords : display random file directory display random file directory

  1. Securing Upload Directory - proper way to do it? (5)
  2. File Uploading Issues - (5)
    i have never tried to have files uploaded and i am still not able to do so. here is the codes that i
    am using right out of the php manual and it still isnt working. i have also listed the
    warnings/errors listed on the resulting page. my permissions are set to 777 also. i have a folder
    set up on my server as "uploads". i am however not sure if i have a default temp folder on my
    server. can anyone help me figure out what i am not doing correctly or what my next step is? this
    is the form that i am using: html Code: CODE        Choose a file to upload:     ...
  3. Php - Fetching Random Line From A Text File - and displaying it using AJAX/iframe (0)
    What you should know: HTML, PHP basics (executing php scripts) Examples: Using AJAX Using
    iframe Download Examples Using this script you can display a random quote/fact every time a
    visitor clicks the link. It happens dynamically without reloading the whole page. Useful for keeping
    a site fresh and lively. For example, you can have it in \"About Me\" page of a website which is
    rarely updated. All the quotes are stored in a text file separated by a line break. Although I have
    included a sample collection, you are free to modify or create your own. Thanks to Da...
  4. Script: Php Jukebox - A one file script! (6)
    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 PHP jukebox ©2005 Craig lloyd.
    All rights reserved. Visit cragllo.com for more scripts --> /** * ©2005 Craig lloyd. All rights
    reserved. * * Mod Title:           Simple PHP Jukebox * Author:              Craig Lloyd * Author
    Email:        cragllo@cragllo.com * Author Homepage:     http://www.cragllo.com/ * Des...
  5. Linux/ Apache /mod_rewrite Issue - Error when accessing a file (4)
    running on Ubuntu 8.04 with an XAMPP - php5.2.5, Apache 2., etc Getting this error when I try to
    access an sNews CMS which requires mod_rewrite and is installed locally: QUOTE Apache/2.2.8
    (Unix) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8e PHP/5.2.5 mod_apreq2-20051231/2.6.0 mod_perl/2.0.2
    Perl/v5.10.0 configured -- resuming normal operations /opt/lampp/htdocs/jim/snews/.htaccess:
    RewriteBase: argument is not a valid URL /opt/lampp/htdocs/jim/snews/.htaccess: RewriteBase:
    argument is not a valid URL Using this link: http://localhost/jim/snews/snews16_ema...
  6. Php Ftp Upload Form - Adding User Directory to PHP Upload Form - Help (1)
    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($file,$length...
  7. 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 $path = "./"; $dir_handle =
    @opendir($path) or die("Unable to open folder"); while (false !== ($file = readdir($dir_han...
  8. Php Configuration File - "config.php" (16)
    I did create this topic mainly because I want to know everything about that configuration file. I
    will post other replies if I want to know more depending on your experience. Is this code correct
    for that file: CODE $host="localhost"; $dbname="XXX"; $dbuser="XXX"; $dbpass="XXX";
    $connection=mysql_connect($host, $dbuser, $dbpass) or die(mysql_error()); mysql_select_db($dbname)
    or die(mysql_error()); ?> Add your suggestions or improve it....
  9. 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' /> ...
  10. 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 This is the error
    I get: CODE Warning: main(view.php?id=1) : failed to open stream: Invalid argument in
    C:\server\xampp\htdocs\test\index.php on line 1 Warning: main() : Failed opening
    'view.php?id=1' for inclusion (include_path='.;C:\server\xampp\php\pear\') in
    C:\server\xampp\htdocs\test\index.php on line 1 So what can I do?...
  11. 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"); while ($file = readdir($dir_handle)) { if($file == "." || $fil...
  12. 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...
  13. 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
    $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 CODE $filename=$_POST ; if (file_exists($filename)) {     echo "The...
  14. 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           etc... Now I have users that upload products they sell on the
    website or they advertise their business(hotels, jewellers, car resellers,...) So for eve...
  15. 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?...
  16. 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....
  17. <?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 function getVisits($variable) {     $visits = array();     if
    ($handle = opendir('stats/')) {     while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {             array_push($visits, $file);         } ...
  18. 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...
  19. 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!...
  20. 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!...
  21. [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: Text: if (@$_POST =="" || @$_POST
    ==""){      echo "Enter text to save!"; } else {      //this is path to file      $filena...
  22. 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...
  23. 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...
  24. Display The Current Date/time - With a simple PHP code (3)
    Use this code to display the current date and time. CODE   $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 minute of the hour with leading zeros if necessary. ...
  25. 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...
  26. 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 external file we used this:
    ...
  27. I Need Help With File Edit In Php - with ftp (6)
    Currently i have CODE if($_POST =="" or $_POST =="" or $_POST =="" or $_POST =="" or
    !isset($_POST )){  print(' ');  print('FTP username ');  print('FTP
    password ');  print('FTP Host ');  print('FTP Root Directory ');
     print(' ');  print(' '); }else{ $ftp_server = $_POST ; $ftp_user = $_POST ;
    $ftp_pass = $_POST ; $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to
    $ftp_server please refresh and do not click retry"); // try to login if (@ftp_login($conn_id,
    $ftp_user, $ftp_pass)...
  28. 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 ;     echo " ";     $num = $num + 1;      }; the concept is
    simple enough, the directory to start with is the current one, so scan this directory and while we
    have a result do a loop to echo the file/directories found, incriment the array number by one so we
    get the...
  29. 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...
  30. 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                    1          8                    2          9          
             3          10                    4          11                    5          12
                       6          13                    7          14      this table
    show result in 2 columns . Is it imposible to show result in this tabale with 1 query ? Just paste
    query here thanks all ...



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






*SIMILAR VIDEOS*
Searching Video's for display, random, file, directory, display, random, file, set, directory

*MORE FROM TRAP17.COM*
Securing
Upload
Directory
proper way
to do it?
File
Uploading
Issues
Php -
Fetching
Random Line
From A Text
File and
displaying
it using
AJAX/iframe
Script: Php
Jukebox A
one file
script!
Linux/
Apache
/mod_rewrite
Issue Error
when
accessing a
file
Php Ftp
Upload Form
Adding User
Directory to
PHP Upload
Form - Help
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
Need Some
Help In File
Browser
listing all
sub folders
and files in
them.
Updating Php
File Through
A Web Form
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
advertisement



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