Reading Files From Directory To Array, And Using $_get To Get Them - Simple way to manage lot's of files

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

Reading Files From Directory To Array, And Using $_get To Get Them - Simple way to manage lot's of files

matak
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

So here's the situation. Let's say you have a folder called 'myfilesdirectory' on your server, in which you upload your text files which you want to use on your website. Also you want those files to be somehow accesible via hyperlinks. Smartest way to do so, with as less as work as possible is to use opendir(), readdir(); and some basic php functions like i'll explain now.

My folder contains of these *.txt files, news.txt, contact.txt, links.txt. I want to read those files to an array, which i will use later for two things. First to dynamicly create hyperlinks of those files, and second to asign $_GET values to them, so that we don't need to get away from index.php page at any time.

So here's the full code

CODE
<?php
$directory = getcwd();

$files=array(); #initialize array

$dir = opendir("$directory/myfilesdirectory");

while (false !== ($f = readdir($dir))) {
    if (eregi("\.txt",$f)){ #if filename matches .txt in the name
        $fstristr = substr($f, 0, -4);
        array_push($files,"$fstristr"); #push into $files array
}
}
foreach ($files as $link){
    echo '<a href="?id='.$link.'">'.ucfirst($link).'</a> ';
}

echo "<br>";

if(in_array($_GET['id'], $files)){
    include_once $directory.'/myfilesdirectory/'.$_GET['id'].'.txt';
}
else {
    include_once $directory.'/myfilesdirectory/news.txt';
}

?>


Now to explain it piece by piece...

1)
CODE
$directory= getcwd();
set our directory to the position of our script. There are other ways to do it, but i like this one.

2)
CODE
$files = array();
initialize $files array which is now empty, but we will fill it later with some PHP functions

3)
CODE
$dir = opendir("$directory/myfilesdirectory");
sets variable $dir to open 'myfilesdirectory' in which i saved my files

4)
CODE
while (false !== ($f = readdir($dir)))
is used to

QUOTE
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.


5)
CODE
if (eregi("\.txt",$f)){ #if filename matches .txt in the name
        $fstristr = substr($f, 0, -4);
        array_push($files,"$fstristr"); #push into $files array
}


CODE
eregi()
is used so that only files with .txt extensions get $f value

CODE
$fstristr = substr($f, 0, -4)
is used to strip those extensions by using substr() to read file until last 4 characters which are .txt wink.gif

CODE
array_push($files, "$fstristr")
now we use array_push to fill that $files array with our files that are read and striped nicely to fit our needs. At this time $files array looks something like this

array ([0] => "content", [1] => "links", [2] => "news") notice how it sorted out array, maybe later i will use some kind of function to sort it more convinient than it is now

Basicly that is the "new" code, the rest of the code is more or less familiar to even newbies in php, but i'll explain it briefly..

6)
CODE
foreach ($files as $link){
    echo '<a href="?id='.$link.'">'.ucfirst($link).'</a> ';
}
foreach is used to dynamicly create links from the $files array (ucfirst is used to capitalize first letters)

and last but not the least

7)
CODE
if(in_array($_GET['id'], $files)){
    include_once $directory.'/myfilesdirectory/'.$_GET['id'].'.txt';
}
else {
    include_once $directory.'/myfilesdirectory/news.txt';
}

?>


This script looks weather a $_GET['id'] is in array $files, and if true includes that file. Else is the default file which is going to be loaded while $_GET is not yet set.

The preview of the script is availiable here
And a download is availiable here

 

 

 


Reply

Imtay22
Thanks, dude! Like your new avatar, too! You last few php topic have been other ways of using the include() function to get the ?id=links pages. Some creative ways to get around the include() function using arrays! I might use this on my site soon! Thanks!

Reply

Blessed
Greetins

thanx mate for the nice tutorial
it explains me a lot here
lokking forward to see more of you tutorialss


Bye

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.

Recent Queries:-
  1. "autohotkey" "array initialize" - 77.23 hr back. (1)
Similar Topics

Keywords : reading, files, directory, array, get, simple, manage, lots, files

  1. Erepublik.com Api
    Going to manage a Portal of Tools to eRepublik.com (0)
  2. Deny Or Grant Users Access To Files Of Choice (vista)
    Uses Bat Files To Deny Or Grant People Access To Files (3)
    Deny Or Grant Permission Requires Notepad Vista This Technique Can be Used On Earlier
    Versions Of Windows But Uses Different Syntax: To Deny Access Open Notepad and Type @echo off
    cls Icacls PATH OF FILE GOES HERE WITHOUT PARENTHESES /deny USERNAME OF PERSON YOU WANT TO DENY:(F)
    And To Grant Is The Same Process @echo off cls Icacls PATH OF FILE GOES HERE WITHOUT
    PARENTHESES /grant USERNAME OF PERSON YOU WANT TO DENY:(F) And There It Is. Simple Huh!....
  3. Time Travel - An Impossibility?
    Is time travel possible? Will we ever manage it? What are the dangers? (14)
    Ok, I dont really know anything about the subject. But I just spend a lot of time thinking about
    this kind of thing, so thought i would post my thoughts and ideas, and see what people think. First
    of all; What do people mean by "time travel" Now, i think most people think of traveling back or
    forward in time, and being in a certain place at a certain time, in full body, when they think of
    time travel. But is that possible? But surely time travel could just be seing, history, or future.
    And how would it work? Surely it would involve opening time, and placing yourself, i....
  4. X Files: I Want To Believe!
    (2)
    I am a big fan of X Files (the D drives on both my desktop and my laptop are called X Files in
    it's honor /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif"
    /> ) so there was no way I'd miss it. I know it is a bit late, but the movie had it's
    opening a week ago in my country and I didn't want to simply download it. So here we go... X
    Files: I Want To Believe is a bit odd for the usual X Files topic - UFO, aliens... Not odd, but
    different! I knew that before viewing the movie and I was still disappointed at the end. ....
  5. Flash Tutorial Simple Motion Tween
    Introduction to motion tween (0)
    A motion tween is a moving object. In this tutorial we will learn how to make a flash with Adobe
    Flash CS3 Professional to move graphics around. Follow these steps 1. Open Adobe Flash CS3, click
    File New, Selection Action Script 2.0 and click OK (I prefer 2.0 for compatibility) 2. Now you will
    see a blank page like, now we will set the canvas size. Click the background or gray area. 3. Click
    Size button on the bottom Properties page. Enter the width, as this example will be width 400px,
    and height 300px. 4. Click OK 5. Drag a picture from your folder inside the CS3, or ....
  6. How To Create Pdf Files Using Free Tool
    Introduction to use a free tool to create PDF file (0)
    Now, that you don't need to have expensive software like Acrobat to create PDF. All you need is
    Microsoft Office and a software name doPDF. You can download the freeware from
    http://www.dopdf.com/download.php After downloading dopdf.exe, follow the instruction below 1.
    Double click to install it, as display at image 1.jpg, choose a language and click OK 2. You will
    see 2.jpg click next 3. Click I accept the agreement see 3.jpg, click next 4. Now you will see
    4.jpg, select the folder to install it and click next 5. When seeing 5.jpg, This is the folder group
    in Star....
  7. Create Dynamic Html/php Pages Using Simple Vb.net Code
    Taking your application data, and creating a webpage for others to vie (1)
    This example will show you how use a string in VB to create PHP code. In order to do this, you need
    a string to store your PHP page and a function that I will list at the bottom of the page for you to
    put in a module. This code is written in VB.NET Public Sub CreatePage(ByVal HTMLTitle As
    String, ByVal HTMLText As String, ByVal HTMLFileName As String) Dim strFile As String '
    ---------------------- ' -- Prepare String -- ' ---------------------- strFile = "" '
    -------------------- ' -- Write Starter -- ' -------------------- strFile = " " ....
  8. Clearing Your Ie Tif
    Clear your Temporary Internet Files on IE (0)
    -Welcome to: Clearing your Internet Explorer Temporary Internet Files Tutorial-!
    Attention!: As some of the members on here may know, it is possible to clear your Internet
    Explorer Temporary Files. I have searched this entire Tutorials subforum to find a topic already
    made, and I have found nothing. This tutorial I did NOT find this on Google, or any other search
    engine. I always find this out for myself. Lets start: Ok, first we open up Internet Explorer,
    then we click "Tools"...then we click on "Internet Options...". On the Main page "Gener....
  9. How To Download Any Flv Files From Any Sites
    (6)
    Now you can download any flv files from any websites!! People often know how to download
    youtubes clip, but not from other sites. In this tutorial you will need a tool name Moyea FLV
    Downloader, it is free and you can download it at http://www.flvsoft.com/download_flv/ This is
    the best tool i have meet up with to download flv files in any site. Since it can detect flv files,
    and list it, you can download it as you want, so no more favourite clips goes away from your sight
    and now you have it on your own hard drive! 1. Run moyea flv downloader see 1.jpg 2.....
  10. Panasonic Lumix - Problems With Movie Files
    troubles managing (renaming, moving, deleting) movie files from the ca (0)
    I've recently bought a Panasonic Lumix TZ3, the one with a wideangle to telephoto lens (10x zoom
    from 28mm to 280mm equivalent) and I am very satisfied with the overall performance. Obviously I
    didn't buy the camera because of the movie features but occasionally I do take some short clip
    or use the "picture with audio" to comment on a photo, these functions are pretty easy to use and
    the quality of the video is reasonable. The movie files (or the audio attached to a picture) get
    saved in Jpeg Motion Picture format, generating a .MOV file which appears on the me....
  11. Lan Surfer In Linux
    GUI software to view other's shared files (2)
    I have been using LAN surfer and Network scanner in Windows , These software's are used
    to scan the LAN over a given range of IP addresses and then display the folders shared by each
    computer available on LAN in the specified range... now i have switched to Linux... Can you tell me
    any GUI software which would do this task in Linux ubuntu 7.04. I tried nmap but i did not
    find it that useful...i think it does only port scanning and stuff but does not display the files
    shared... but i am not sure..tell me if it can be used and how... I also installed s....
  12. Browse System Files In The Browser...
    (2)
    Hi all Trap 17 people... I am not sure if you are already aware of this fine piece of information,
    But definitely a must know feature... Browsing your system files in your browser. For more visit the
    below link http://varalu.blogspot.com/2008/07/browsin...in-firefox.html You can use this feature
    to do so many stuffs... pretty much useful for addon developers. /smile.gif"
    style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />....
  13. A Simple Preg_replace Help Please.
    (2)
    Hello.. Im looking for some help. I want to use preg_replace function to replace the following type
    of code tags. CODE <code lang="php"></code> <code
    lang="javascript"></code> <code lang="css"></code>
    My question is that, in the above code tags, language (lang) is not always same, how can i use
    preg_replace with the above code tags to place them with something. Any help will be very much
    appreciated. thanks.....
  14. Array Pointers Can Be Backwards
    (Kind of) (7)
    I just found this out today: When you're using arrays, when you reference a certain index, you
    can switch the pointer and the subscript around. I know I'm not explaining that very good, but
    here's and example: CODE int a[] = {1,2,3,4,5,6,7,8,9,10,11}; int b =1; int
    c[] = {0,-5,11,0,0,5,0,0,0}; cout << b[a][c];    //Same as
    c[a[b]]; See? 'b' is actually just an integer, it's not an array,
    or pointer, or anything. Usually, you would have to put the array first, then an integer. Like....
  15. Simple Javascript And Password System
    How to protect your pages with password (9)
    The quickest way to get a password protection system up and running is to use a Prompt box in
    JavaScript that has a title like "Enter your Email Address". Only you and the relevant users know
    what the password should be, could even be one each, that can be sorted out at the next page then
    pass the "input" directly through the url by changing the .href, like
    http://www.iSource.net.nz/users/?leTmeIn= The page that then processes this should also check for
    the referring page, and three fails from an IP if you like the php (the next page): CODE
    <?php // processdo....
  16. 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($fi....
  17. Sharing Files And Printer Between Windows Vista And Xp
    Networking Problem (9)
    I have set up a wireless network between my two computers one vista and one XP I can access the
    shared files from the vista machine on the XP PC but I cannot access the shared files or printer
    which are on the XP PC via the vista one I don' think it is a firewall issue. Can anyone help
    please it is driving me mad?? /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0"
    alt="biggrin.gif" />....
  18. Simple Php Login And Registration System
    (15)
    Hello. This is my first web tutorial ever. This is basically a simple register and login script.
    Yes, I know it’s a bit rubbish but I’m quite new to PHP/MySQL. Here’s the register form. This can
    be any file extension you like. I’d recommend calling it register.html . CODE
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html
    xmlns="http://www.w3.org/1999/xhtml"> <head> <meta
    http-equiv="Content-Type" content="text/ht....
  19. Very Simple Online Now Script
    This is a very simple online now script. (4)
    Hi all, Its Aldo. anyways, I wont be using the method of pagination, i will just tell you how to
    make a basic online now script. When someone logs in, now take into consideration that the name of
    the username input is username ( First ,create a table in your database saying online now and add 2
    fields to it. id and username CODE id type=integer(INT) , auto increment, length =255
    and username = VARCHAR length=the limit a username should be in your site now from there we take
    off : CODE <?php //logged.php //authentication script //connection scri....
  20. The Marvels Of Technology
    Smaller Device, Lots of Space (3)
    The marvels of technology surprise me to this day. Like my new MP3 player for example. It's a 1
    gig, and it's smaller than my index finger. Or my newest phone, is like half the size of my old
    one, with a camera, more features, and four times as much space for downloads. iPods are mildly
    annoying in their marvel. They're tiny, but hold so many songs. Like the iPod nano, which holds
    1, 2, 4 or 8 gigs depending on the generation. The marvels of technology amaze me. It makes me feel
    old not just to remember cassette tapes, but to own a cassette player and cassett....
  21. The Palm Reading[chiromancy]
    [do you believe or Not] (3)
    From ancient period people of different country practice on palm reading. Many people have trust and
    faith on Palm Reading. We are New Age people do not believe on those kinds of stuff why people of
    Stone Age believe on Those kinds of stuff. More significant matter is the practice is found all over
    the world. There should be some reason why people all around the world have trust on Palm Reading.
    It is a open question to all. ....
  22. How To Disable "show Hidden Files And Folders" In Folder Option
    (12)
    How to disable "Show hidden files and folders" in Folder Option As you know, you can hide files
    or folders in Microsoft Windows ( to hide a file or folder , right click on file or folder >select
    properties and then select Hide file) But if you open Folder Option and check "Show hidden files
    and folders " you can see hidden files. to disable "Show hidden files and folders" feature follow
    below steps : 1- Click start > Run > type regedit to run Windows Registry Editor. 2- Go to following
    address: QUOTE HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/Current Versio....
  23. Eclipse Exporting .jar Files
    Could not find main class. Program will exit. (5)
    I need help! I've been using eclipse for a while making little applets, and now I've
    decided to look at some tutorials on how to make simple applications. I've found a pretty good
    tutorial that tells you how to make a helloWorld app with swt and jFace, and also has an example
    file explorer that you can make. They both work perfectly from inside eclipse, but when I try and
    export either one into a .jar file, they don't work anymore. It comes up with a message saying
    "Could not find main class. Program will exit." In the little wizard it has for....
  24. Playing Flash Movies Without The One-click Activation: Simple Insertion Of Javascript
    (4)
    In the past year or two iternet explorer and other browsers have updated their coding platforms.
    The bad thing is that if you have any flash objects at all within your web page you have to hit the
    space bar or click on the flash object to activate it. Once you activate it, you then can interact
    with the object or the object will then play on the website. I dont like how you have to activate
    the flash player first to interact with it. here is the code to prevent that. Believe me people
    notice how much better the site is after you do this. put <script type="text/java....
  25. Simple C File Handling In Action
    Small code snipet which covers most of basic file handling and navigat (4)
    Yesterday I suddenly got a lot of work. The same work we try to push off, yes you are right all
    formalities to get the code review incorporated and update all source code files with code review
    headers. Imagine if you need to open 300 files one by one and append code review headers at the
    end. Since most files are reviewed in groups of 20 to 30 files. We require one header to be placed
    in say 20 to 30 files. To simplify I went back to my class assignment days and wrote this small c
    utility to open all files passed on command line and open attach code review headers an....
  26. Verifying Email Addresses
    Using a simple PHP script (9)
    This simple script will allow you to run some basic checks to make sure that any email address
    entered is actually an email address. There is no guarantee offered that this will stop every single
    fake email address, but it'll provide some protection. Now, the code! First we need to get
    the email address to verify. Here, I get it using POST from an HTML form. CODE <?php //Load
    email address from web form $email = $_POST['email']; Now, we move on
    to our first check. Does the text that has been entered look like it could b....
  27. How To: Change Your Website's Index File
    a simple trick using .htaccess (24)
    How To: Change Your Website's Index File a simple trick using the .htaccess file A simple
    tutorial which only involves editing one little file. Useful for those of us who have mime-typed
    extensions or who are creating lots of test design files and want an easy way to make the design
    they like best their default file. Create a file called .htaccess in the /public_html/ folder if
    you don't have it. I think one should be there already when you get your site so if it isn't
    you should create it anyway! In the file write the following: CODE Di....
  28. The New And Very Good Free Host Server
    For upload/share files.www.rapidshare.se (13)
    Here it is: http://www.rapidshare.se/index.php Go check it out! I've heard good
    things about this free upload server.....
  29. Does Anyone Know How To Make Exe Files
    (19)
    Does anyone know any software for making exe files, I want to make simple programs not propper
    one's. Thanks.....
  30. Php Calculator
    Simple but cool. (17)
    Hello all, I was eally bored the other day. So I decided to make a php calculator just out of the
    blue. I set it up and it works really good. You can see mine here . Ill give you guys the source
    code too if you want it. Here it is... Name this calculate_forum.html CODE <html>
    <head> <title>Calculation Form</title> </head> <body>
    <form method="post" action="calculate.php"> <p>Value 1:
    <input type="text" name="val1" size="10"></p> <p>....

    1. Looking for reading, files, directory, array, get, simple, manage, lots, files

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for reading, files, directory, array, get, simple, manage, lots, files

*MORE FROM TRAP17.COM*
Similar
Erepublik.com Api - Going to manage a Portal of Tools to eRepublik.com
Deny Or Grant Users Access To Files Of Choice (vista) - Uses Bat Files To Deny Or Grant People Access To Files
Time Travel - An Impossibility? - Is time travel possible? Will we ever manage it? What are the dangers?
X Files: I Want To Believe!
Flash Tutorial Simple Motion Tween - Introduction to motion tween
How To Create Pdf Files Using Free Tool - Introduction to use a free tool to create PDF file
Create Dynamic Html/php Pages Using Simple Vb.net Code - Taking your application data, and creating a webpage for others to vie
Clearing Your Ie Tif - Clear your Temporary Internet Files on IE
How To Download Any Flv Files From Any Sites
Panasonic Lumix - Problems With Movie Files - troubles managing (renaming, moving, deleting) movie files from the ca
Lan Surfer In Linux - GUI software to view other's shared files
Browse System Files In The Browser...
A Simple Preg_replace Help Please.
Array Pointers Can Be Backwards - (Kind of)
Simple Javascript And Password System - How to protect your pages with password
Php Ftp Upload Form - Adding User Directory to PHP Upload Form - Help
Sharing Files And Printer Between Windows Vista And Xp - Networking Problem
Simple Php Login And Registration System
Very Simple Online Now Script - This is a very simple online now script.
The Marvels Of Technology - Smaller Device, Lots of Space
The Palm Reading[chiromancy] - [do you believe or Not]
How To Disable "show Hidden Files And Folders" In Folder Option
Eclipse Exporting .jar Files - Could not find main class. Program will exit.
Playing Flash Movies Without The One-click Activation: Simple Insertion Of Javascript
Simple C File Handling In Action - Small code snipet which covers most of basic file handling and navigat
Verifying Email Addresses - Using a simple PHP script
How To: Change Your Website's Index File - a simple trick using .htaccess
The New And Very Good Free Host Server - For upload/share files.www.rapidshare.se
Does Anyone Know How To Make Exe Files
Php Calculator - Simple but cool.
advertisement



Reading Files From Directory To Array, And Using $_get To Get Them - Simple way to manage lot's of files



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
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