How to check if directory directory has text files?

Discussion in 'PHP' started by Alvin, Mar 3, 2007.

  1. #1
    Hello

    I would like to know how can i check with php that if directory contains .txt files.
    ? :confused:


    Thanks
     
    Alvin, Mar 3, 2007 IP
  2. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This should do the trick:

    
    $dir = "/target_dir";
    $dh  = opendir($dir);
    while (false !== ($filename = readdir($dh)))
      {
     if( preg_match( '/\.txt$/', $filename)) { $files[] = $filename; }
     }
    
    sort($files);
    print_r($files);
    
    PHP:
     
    clancey, Mar 3, 2007 IP
  3. Alvin

    Alvin Notable Member

    Messages:
    2,076
    Likes Received:
    164
    Best Answers:
    0
    Trophy Points:
    210
    #3
    thanks for your help.. but I just want to check the files not print....

    and if it doesnt exist I want to terminate scirpt...

    i tried tweaking your code but doesnt work..
     
    Alvin, Mar 3, 2007 IP
  4. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #4
    My example code cannot solve your specific problem because I cannot guess what you are trying to do.

    What this code does is recursively check a directory to see if it contains files with the extension ".txt". It collects them into an array.

    Instead of sorting and printing them -- to demonstrate that the code works -- you can test to see if the first element in the array is set. This is element "0" in the array.

    If it is not set or empty, then you exit or return, knowing that you have found no files with the extention ".txt". If it is set, then you would need to write the code to do what you intend with any files which end in the extension .txt. For instance:

    if(!isset($files[0]) ) { print "exit . . . no text files\n"; return(); } 
    else { print "do something because there are *./txt files\n"; }
    PHP:
    If this is in a function, which is being called by another part of your or another script, you want to return() from this function and continue processing in the orginal script. When you call exit(), the script terminates.
     
    clancey, Mar 4, 2007 IP
  5. Chemo

    Chemo Peon

    Messages:
    146
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Chemo, Mar 5, 2007 IP