1

I am looping through a list of files in a directory and I want to match a substring that I have with the filename. If the filename contains the substring then return that file name so that I can delete it. I have done the following and its just returning everything:

while ($file = readdir($dir_handle)) { 

        $extension = strtolower(substr(strrchr($file, '.'), 1)); 
        if($extension == "sql" || $extension == "txt" ) {

            $pos = strpos($file, $session_data['user_id']);

            if($pos === true) {
                //unlink($file);
                echo "$file<br />"; 
            }else {
                // string not found
            }   
        }
} 

What am I doing wrong?

Thanks all for any help

4 Answers 4

4

strpos returns an integer or FALSE. You'll want to update your test to be

$pos !== FALSE 

Then - if you want to delete the file you can uncomment the unlink() call. I'm not sure what you mean by "return so I can delete".

1
  • Fantastic! I didn't try that combination! :P
    – Abs
    Jan 7, 2010 at 0:58
1

Assuming you are on Linux you can do this using the [glob()][1] function with the GLOB_BRACE option:

$files = glob('*.{sql,txt}', GLOB_BRACE);

You might also mix in the user_id there.

Not sure if it works on Windows. See http://de.php.net/glob and mind the note about the GLOB_BRACE option.

0
if ($handle = opendir('/path/to/dir/') {
    $extensions = array('sql' => 1, 'txt' => 1);
    while (false !== ($file = readdir($handle))) { 
        $ext = strtolower(substr(strrchr($file, '.'), 1)); 
        if (isset($extensions[$ext]) && strpos($file, $session_data['user_id']) !== false)
            echo "$file<br />"; 
        else
            echo "no match<br />";
        }
    }
} 
0

you can use SPL to do it recursively

foreach (new DirectoryIterator('/path') as $file) {
    if($file->isDot()) continue;
    $filename = $file->getFilename();
    $pathname = $file->getPathname();
    if ( strpos ($filename ,".sql") !==FALSE ) {
        echo "Found $pathname\n";
        $pos = strpos($filename, $session_data['user_id']);
        ......
        #unlink($pathname); #remove your file
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.