Search code examples
phpmovereaddir

Search inside all files of a Directory and then move using PHP


I have some issues, I need to search an specific text inside all the files of a directory, if the text appears inside one or more TXT I need to copy the file to two folders, and then delete the original one.

This is the code that I have so far (I know it's nothing)

<?php
$dir = 'C:\Users\ramosala\Desktop\New folder (2)';
if (is_dir($dir)) {
    if ($dh = scandir($dir)) {
        while (($file = readdir($dh)) !== false) {
            $Word="serie      = SMO";   
            if ($Word){
                echo "La factura pertenece a Coppel";
                $encuentra=TRUE;
                copy('C:\Users\ramosala\Desktop\New folder(2)',     'C:\Users\ramosala\Documents\Prueba Coppel\'');
                copy('C:\Users\ramosala\Desktop\New folder(2)', 'C:\Users\ramosala\Documents\Prueba Coppel 2\'');
                unlink('C:\Users\ramosala\Desktop\New folder(2)');
            }
            if($encuentra!=TRUE){
                echo 'No Pertenece a Coppel';

            }           
        }
    }
}

?>

Solution

  • Full prototype:

    $sDirectory     = 'file-fun';
    $sNewDirectory  = 'file-fun2';
    $sNewDirectory2 = 'file-fun3';
    if( !is_dir( $sNewDirectory ) )
    {
        mkdir( $sNewDirectory, 0777, TRUE );
    }
    if( !is_dir( $sNewDirectory2 ) )
    {
        mkdir( $sNewDirectory2, 0777, TRUE );
    }
    $sFilter = '12';
    if( is_dir( $sDirectory ) ) 
    {
        $rDir = opendir( $sDirectory );
        while( ( $sFile = readdir( $rDir ) ) !== FALSE ) 
        {
            if( ( $sFile == '.' ) || ( $sFile === '..' ) )
            {
                continue;
            }
            $sFilePath = $sDirectory . '/' . $sFile;
            $sContents = file_get_contents( $sFilePath );
            if( strpos( $sContents, $sFilter ) !== FALSE )
            {
                $sNewFileName  = $sNewDirectory . '/' . $sFile;
                $sNewFileName2 = $sNewDirectory2 . '/' . $sFile;
                if( !copy( $sFilePath, $sNewFileName ) || !copy( $sFilePath, $sNewFileName2 ) )
                {
                    echo 'Could not move: ' . $sFile;
                }
                else
                {
                    unlink( $sFilePath );
                }
            }
        }
    }