Nov 21, 2009

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

free web hosting
Open Discussion > MODERATED AREA > 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

Comment/Reply (w/o sign-up)

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

 

 

 


Comment/Reply (w/o sign-up)

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?

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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.

Comment/Reply (w/o sign-up)

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.

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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 :-)

Comment/Reply (w/o sign-up)



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*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : display, random, file, directory, display, random, file, set, directory

  1. Securing Upload Directory
    proper way to do it? (6)
  2. 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 Davi....
  3. 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....
  4. Php Configuration File
    "config.php" (18)
    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.....
  5. 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....
  6. 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....
  7. How To Display Images Of A Directory
    (5)
    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 Ftp Upload Form
    Adding User Directory to PHP Upload Form - Help (2)
    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: CODE //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,$....
  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
    $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....
  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           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....
  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 function getVisits($variable) {     $visits = array();     if
    ($handle = opendir('stats/')) {     while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {             array_push($visits, $file);         } ....
  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: Text: if (@$_POST =="" || @$_POST
    ==""){      echo "Enter text to save!"; } else {      //this is path to file      $filena....
  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 (4)
    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. ....
  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 external file we used this:
    ....
  23. How To Sort Files Of A Directory using Php
    (13)
    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 " $file "; } } //closing the directory
    closedir($dir....
  24. 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?....
  25. 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:     ....
  26. Error When Using file_put_contents()
    failed to call to undefined function (5)
    Hey all, I decided to write a script which writes some text to a file, but I have a problem when I
    execute the script, I get a fatal error: QUOTE(homepage) Fatal error : Call to undefined
    function: file_put_contents() in /home/cmatcme/public_html/afile.php on line 55 This is the
    code I'm using to write the file: $ipfnsdoc = "/home/cmatcme/public_html/afolder/afile.txt";
    if (!is_readable($ipfnsdoc)) { echo "File cannot be read"; $stopload = 1; } if
    (!is_writable($ipfnsdoc)) { echo " \nFile cannot be written to"; $stoploa....
  27. 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....
  28. 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' /> ....
  29. Random Message Generator
    (8)
    Here comes another one of Inspired's "amazing" PHP scripts. This little script lets you display
    a random message every time the user visits that particular page. It's not really that useful,
    but it does make the page a bit more "dynamic". CODE $randMsg = array("Hi, welcome to my
    page!", "Hey you! Thanks for visiting!", "Bonjour, mon ami!", "So, do you like the site?", "Come
    one, come all!"); $MsgNum = count($randMsg); $MsgGenNum = floor(rand(MsgNum)); echo $randMsg ;
    You can edit those values in the array if you want. Add more if you so choose. Enj....
  30. Pages In 1 File
    ?? (10)
    I know its possible to put many pages inside 1 file. But how? Lets say you have a guestbook with
    different pages for signing and viewing. How to make so those pages are in 1 file? /huh.gif"
    style="vertical-align:middle" emoid=":huh:" border="0" alt="huh.gif" />....

    1. Looking for display, random, file, directory, display, random, file, set, directory
Similar
Securing Upload Directory - proper way to do it?
Php - Fetching Random Line From A Text File - and displaying it using AJAX/iframe
Linux/ Apache /mod_rewrite Issue - Error when accessing a file
Php Configuration File - "config.php"
Need Some Help In File Browser - listing all sub folders and files in them.
Updating Php File Through A Web Form
How To Display Images Of A Directory
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
How To Sort Files Of A Directory using Php
Include File.php?id=something - using the include() function
File Uploading Issues
Error When Using file_put_contents() - failed to call to undefined function
Script: Php Jukebox - A one file script!
Getting List Of Directories And Files Using Php - PHP Function for Directory and File List
Random Message Generator
Pages In 1 File - ??

Searching Video's for display, random, file, directory, display, random, file, set, directory
See Also,
advertisement


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

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com