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 4 of 4
  1. #1
    Regular Coder
    Join Date
    Feb 2007
    Posts
    217
    Thanks
    25
    Thanked 1 Time in 1 Post

    Finding certain files in a directory

    I want to display all files in a directory on my host which start with certain characters.



    I've written this coding:
    PHP Code:
    <?php
    // Find all files which start with 2922A
    $fn "2922A";
    $path __DIR__;

    $files scandir($path);

    print 
    'Files in path you entered:<br>';

    foreach (
    $files as $value) {
        print 
    $value '<br>';
        if (
    file_exists($path '/' $fn)) {
            
    $conf 1;
        }
        else {
            
    $conf 0;
        }
    ?>
    }

    if ($conf == 1) {
        print 'File exists<br>';
    }
    but this returns every file in the directory. How can I alter my coding so that only the desired files are displayed ? I guess it's something with substr?

  • #2
    Regular Coder patryk's Avatar
    Join Date
    Oct 2012
    Location
    /dev/couch
    Posts
    398
    Thanks
    2
    Thanked 64 Times in 64 Posts
    use glob() instead

    PHP Code:
    $files glob('/home/someone/somedir/abc*');
    foreach(
    $files as $value){
        echo 
    $value '<br />';

    this will display everything matching /home/someone/somedir/abc*
    Last edited by patryk; 03-29-2013 at 01:05 AM.

  • Users who have thanked patryk for this post:

    docock (03-29-2013)

  • #3
    Regular Coder patryk's Avatar
    Join Date
    Oct 2012
    Location
    /dev/couch
    Posts
    398
    Thanks
    2
    Thanked 64 Times in 64 Posts
    i just realized that code i gave you will output directories as well.
    here's a fix for that:
    PHP Code:
    $files glob('/home/someone/somedir/abc*');
    foreach(
    $files as $value){
        if(
    is_file($value)){ //check if it's a file
            //basename() strips path leaving only file name
            
    echo  basename($value) . '<br />';
        }


  • Users who have thanked patryk for this post:

    docock (03-29-2013)

  • #4
    Regular Coder
    Join Date
    Feb 2007
    Posts
    217
    Thanks
    25
    Thanked 1 Time in 1 Post
    Thanks it works perfectly!!


  •  

    Posting Permissions

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