简体   繁体   English

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

[英]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.我正在尝试重命名我的临时上传文件夹中的所有文件,而是给文件一个唯一的 ID 参考号作为文件名,后跟应该在每次重命名后增加的_x后缀,从而产生诸如myidnumber_1.jpg, myidnumber_2.jpg, etc.类的文件名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++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM