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