gpt4 book ai didi

php - 如果文件已存在,则重命名文件

转载 作者:行者123 更新时间:2023-12-02 07:29:15 24 4
gpt4 key购买 nike

我正在尝试上传文件并重命名它(如果它已经存在)。
我想要我做的方式是,当 det 相同的文件上传时,名称只添加 1,然后是 2,然后是 3,依此类推。

示例:如果文件“file”存在,则新文件应该是“file1”,然后是下一个“file2”。

我在网上看到了一些例子,但没有任何我认为适合我的代码的例子(菜鸟)

这是我现在的代码:

$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf") {die("You can only upload PDF files");}

// Checking filesize
if ($_FILES['dok']['size']>1048576) {die("The file is too big. Max size is 1MB");}

// Check if user have his own catalogue
if (file_exists("filer/".$id."/")) {
// Moving the file to users catalogue
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);}

//If user don't have his own catalogue
else {
// Creates new catalogue then move the file in place
mkdir("filer/".$id);
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname); } }

有人可以帮我写代码来解决这个问题吗?
非常感谢!

最佳答案

$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf") {
die("You can only upload PDF files");
}
// Checking filesize
if ($_FILES['dok']['size']>1048576) {
die("The file is too big. Max size is 1MB");
}

if(!is_dir("filer/".$id."/")) {
mkdir("filer/".$id);
}

$rawBaseName = pathinfo($fname, PATHINFO_FILENAME );
$extension = pathinfo($fname, PATHINFO_EXTENSION );
$counter = 0;
while(file_exists("filer/".$id."/".$fname)) {
$fname = $rawBaseName . $counter . '.' . $extension;
$counter++;
};

move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);

}

但是不要忘记保护您的脚本(例如,请参阅上面 Marc B 的评论),也许您可​​以优化更多 ;-)

关于php - 如果文件已存在,则重命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23963734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com