Thursday, April 30, 2009

Remove files names unwanted characters

/* Your file path to remove the files names unwanted characters */

$path_file = "/www/htdocs/phpdocs/missing_man";
$extra_character = "-";
$replace_character = "_";
$valid_file_extn = "mp3";
$max_filename_len = 50;

/* Calling function : Removing the unwanted characters */
Remove_unwanted($path_file, $extra_character, $replace_character, $valid_file_extn, $max_filename_len);

/* Function Definition : Remove unwanted files */
function Remove_unwanted($path, $extra_character, $replace_character, $valid_file_extn, $max_filename_len){
$path_dir = opendir($path);
while (($files = readdir($path_dir)) !== false) {

if (Valid_file($files, $valid_file_extn)) {
$check_file = str_replace($extra_character, $replace_character, $files);

/* Check Max length of Filename and removes excess characters */
$check_file = Valid_file_length($check_file, $max_filename_len, $valid_file_extn);

@rename($path."/".$files, $path."/".$check_file);
print($path."/".$check_file); echo "
";

}
}
}

/* Calling Function : Valid File extension or not */
function Valid_file($file, $extn){
if ($file !="" && $extn != ""){
$x = explode(".", $file);
if ($x[1] == $extn) return 1; else return 0;
}
}


/* Check Max length of Filename and removes excess characters */
function Valid_file_length($file, $max_filename_len, $valid_file_extn){
if ($file !="" && $max_filename_len != "" && $valid_file_extn != ""){
$x = explode(".", $file);
if (strlen($x[0]) > $max_filename_len) {
$check_file = substr($x[0], 0, $max_filename_len);
return $check_file . "." . $valid_file_extn;
} else {
return $file;
}
}
}

more info.. http://evergreenphp.blogspot.com

No comments: