Twitter / Ptlouco

terça-feira, 12 de maio de 2009

PHP renaming filenames within a directory

0

This'll be my first post about PHP, i love PHP(!)

Today i'll talk about sanitize all files within a directory, so, this code will:
  • Replace all spaces by underscores
  • Lowercase all chars
  • Remove any non letter or number in filename



<?

/**
* Function to get 'correct' filename
*/
function sanitizeFileName( $filename ) {

    // Replace spaces with underscores
    $filename = str_replace( " ", "_", $filename );

    // Remove non letters, numbers, '-', '_' and dots from filename
    $filename = preg_replace( "/[^aA-zZ0-9\-_\.]+/i", "", $filename );

    // Lower filename string
    $filename = strtolower( $filename );

    return $filename;


}

// Renaming files within a directory

$path = "./path_to_files/";

if ( $handle = opendir( $path ) ) {

    // For each file sanitize it.
    while( false !== ( $file = readdir( $handle ) ) ) {

        // We don't want . and ..
            if( $file != "." and $file != ".." ) {

            $correctFilename = sanitizeFileName( $file );
            // We only want "incorrect" filenames
            if( $file != $correctFilename ) {

                // rename file to his new name
                echo "Renaming $file to $correctFilename";
                rename( $path . $file, $path . $correctFilename );

            }
            else {
                echo "Renaming $file is already normalized";
            }

        }
    }
    closedir($handle);
}

?>