简体   繁体   中英

PHP - rename files in temp folder

I am trying to rename all files I have in my temporal upload folder and instead give the files a unique ID reference number as filename followed by _x suffix that is supposed to increase after each rename, resulting in file names such as myidnumber_1.jpg, myidnumber_2.jpg, etc.

Problem is, my code doesnt seem to like the rename command and also does not keep the file extension. Any suggestions on how to address this?

// Get array of all files in temp folder and rename
$check_folder = scandir("../../pages/fo_dmlog/attachments/".$_SESSION['Holidex']."/temp/".$_SESSION['myusername']."/");
$n = 1;

foreach ($check_folder as $check_file) {
    if (in_array($check_file, array(".",".."))) continue;

    $newName = str_replace($check_file,$logID."_".$n,$check_file);
    rename($check_folder . $check_file, $check_folder . $newName);

    echo "Attachment: $check_file<br>";
    $n++;
}

EDIT:

// Get array of all files in temp folder and rename
$check_folder = scandir("../../pages/fo_dmlog/attachments/".$_SESSION['Holidex']."/temp/".$_SESSION['myusername']."/");
$logID = "132456";
$n = 1;

foreach ($check_folder as $check_file) {
    if (in_array($check_file, array(".",".."))) continue;

    $extension = end(explode(".", $check_file));
    $newName = str_replace($check_file,$logID."_".$n.$extension,$check_file);
    rename($check_folder . $check_file, $check_folder . $newName);

    // instead of rename, can also move the files right away
    //move_uploaded_file($newName, "../".$logID."/" .$newName);

    echo "Attachment: $newName<br>";
    $n++;
}

Thanks for the feedback, the following code works:

// Get array of all files in temp folder and rename
$dir = "../../pages/fo_dmlog/attachments/".$_SESSION['Holidex']."/temp/".$_SESSION['myusername']."/";
$check_folder = scandir($dir);
$n = 1;

foreach ($check_folder as $check_file) {
    if (in_array($check_file, array(".",".."))) continue;

    $extension = end(explode(".", $check_file));
    $newName = str_replace($check_file,$n.'.'.$extension,$check_file);
    rename($dir . $check_file, $dir . $newName);

    // instead of rename, can also move the files right away
    //move_uploaded_file($newName, "../".$log_ID."/" .$newName);

    echo "Attachment: $newName<br>";
    $n++;
}

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