简体   繁体   中英

Php: append extension to all files with no extension in a folder

I have a folder called MyFolder with these three files:

file1 file2 file3.gif file.html

I need to add the extension '.gif' to the files with no extension. Then the first file1 and second file2 files should be targeted.

Result should be:

file1.gif file2.gif file3.gif file.html

The files are gif files, but somehow they lost the extensions. If I add the extension manually (editing its names) then I can load correctly in the browser

I'm trying with this code:

$directory = "http://www.example.com/MyFolder/";
if ($handle = opendir($directory)) { 
    while (false !== ($fileName = readdir($handle))) {   

        if($fileName['extension'] == ""){

            $fileName = $fileName.".gif";
        }
        rename($directory . $fileName, $directory . $newName);
    }
    closedir($handle);
}

Unfortunately because you can't pass preg_grep into array_walk this had to be split like so, otherwise it could have been a single line.

$dir='./MyFolder/';
$col=preg_grep( '@^((?!gif).)*$@i', glob( $dir . '*' ) );

array_walk( $col , function($f){
    rename( $f, $f.'.gif' );
});

Or, a modified version of the original

if( $handle = opendir( $directory ) ) { 
    while( false !== $filename = readdir( $handle ) ) {
        if( !is_dir( $filename ) ) {
            $file = $directory . $filename;
            if( empty( pathinfo( $file, PATHINFO_EXTENSION ) ) ){
                rename( $file, $file . '.gif' );
            }
        }
    }
    closedir($handle);
}

As the original above happily renamed files with extensions other than gif a more simple version without the faulty regex seems to work OK.

$dir='c:/temp/fileuploads/1/';
$col=glob( $dir . '*' );

array_walk( $col, function( $f ){
    if( empty( pathinfo( $f, PATHINFO_EXTENSION ) ) ){
        printf('%s - %s<br />',$f,$f.'.gif');
        rename( $f, $f.'.gif' );
    }
});

Change your rename to add the .gif extension after you've detected that it is missing. Your current code was using a variable $newname that didn't exist.

while (false !== ($fileName = readdir($handle))) {   

        if($fileName['extension'] == ""){
           rename($directory . $fileName, $directory . $fileName . '.gif');
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM