以下代码旨在遍历图像目录并重命名它们。
我让它运行良好,但我想在文件开头添加一个“静态”标记,一旦重命名,它将在未来忽略。
例如,假设我们有一个包含 100 个文件的目录。
其中前 20 个名称为“image-JTzkT1RYWnCqd3m1VXYcmfZ2nhMOCCunucvRhuaR5.jpg”,后 80 个名称为“FejVQ881qPO5t92KmItkNYpny.jpg”,这绝对可以是任何东西。
我想忽略已经重命名的文件(由文件名开头的“图像-”表示)
我怎样才能做到这一点?
<?php
function crypto_rand_secure($min, $max) {
$range = $max - $min;
if ($range < 0) return $min; // not so random...
$log = log($range, 2);
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd >= $range);
return $min + $rnd;
}
function getToken($length){
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
for($i=0;$i<$length;$i++){
$token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
}
return $token;
}
$dir = "/path/to/images";
if ( $handle = opendir ( $dir)) {
echo "Directory Handle = $handles<br />" ;
echo "Files: <br />" ;
while ( false !== ($file = readdir($handle))) {
if ( $file != "." && $file != ".." ) {
$isdir = is_dir ( $file ) ;
if ( $isdir == "1" ) {} // if its a directory do nothing
else {
$file_array[] = "$file" ; // get all the file names and put them in an array
//echo "$file<br />" ;
} // closes else
} // closes directory check
} // closes while
} // closes opendir
//Lets go through the array
$arr_count = count( $file_array ) ; // find out how many files we have found so we can initiliase the counter
for ( $counter=1; $counter<$arr_count; $counter++ ) {
echo "Array = $file_array[$counter] - " ; // tell me how many files there are
//$new = str_replace ( "C", "CIMG", $file_array[$counter] ) ; // now create the new file name
$new =getToken(50);
//if (substr($file_array[$counter]), 0, 3) == "gallery_image")
//{
//}
//else
//{
$ren = rename ( "$dir/$file_array[$counter]" , "image-$dir/$new.jpg" ) ; // now do the actual file rename
echo "$new<br />" ; // print out the new file name
//}
}
closedir ( $handle ) ;
?>