PHP - 重命名临时文件夹中的文件

时间:2017-01-25 06:08:24

标签: php rename

我正在尝试重命名我的临时上传文件夹中的所有文件,而是给文件一个唯一的ID引用号作为文件名后跟_x后缀,该后缀应该在每次重命名后增加,从而产生文件名例如myidnumber_1.jpg, myidnumber_2.jpg, etc.

问题是,我的代码似乎不喜欢重命名命令,也不保留文件扩展名。有关如何解决此问题的任何建议吗?

// 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++;
}

编辑:

// 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++;
}

1 个答案:

答案 0 :(得分:1)

感谢您的反馈,以下代码有效:

// 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++;
}