Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    Dec 2004
    Posts
    202
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Php Help-Getting files

    what commands will return all the files of a directory in a array. Or something along that line.

  • #2
    Regular Coder
    Join Date
    May 2005
    Posts
    100
    Thanks
    0
    Thanked 0 Times in 0 Posts
    PHP Code:
    <?php
    $save_in_array
    =file('my_file.dat');
    ?>

  • #3
    Regular Coder
    Join Date
    Dec 2004
    Posts
    202
    Thanks
    0
    Thanked 0 Times in 0 Posts
    No not a file but all files in a folder

  • #4
    teh Moderatorinator
    Join Date
    Sep 2004
    Location
    USA
    Posts
    2,472
    Thanks
    4
    Thanked 40 Times in 40 Posts
    PHP Code:
    <?php

    function arrFiles ($dir)
    {
        
    $handle opendir($dir);

        while (
    $file readdir($handle))
        {
            if (
    $file != '.' && $file != '..')
            {
                
    $fileArr[] = $file;
            }
        }

        
    closedir($handle);
        return 
    $fileArr;
    }

    $f arrFiles("C:\\");

    foreach(
    $f as $allFiles)
    {
        echo 
    $allFiles "<br>";
    }

    ?>
    Could be better...

  • #5
    Regular Coder
    Join Date
    Feb 2005
    Location
    West Midlands, UK
    Posts
    623
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Just a couple of things with that. Firstly, I don't know how it works on IIS, but on a *nix machine directories are files, too. Therefore the function returns not only files in the directory but sub directories too (which is fine if that's what you want, but just be aware that it's happening). Also, due to the way while loops work you will always receive one empty array on the end which serves no purpose.

    Here's a slight re-working which strips out all directories and empty arrays and leaves you just the filenames:

    PHP Code:
    function get_filenames($dir='.') {
        if (
    $handle opendir($dir)) {
            while (
    false !== ($file readdir($handle))) {
                
    $check_file = (!empty($file) && !is_dir($file) ? $file '');
                if(!empty(
    $check_file)) {
                    
    $return_file[] = $check_file;
                }
            }
            
    closedir($handle);
            return 
    $return_file;        
        }
    }

    print_r(get_filenames()); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •